<?php

// power by wshoto.com
if (!defined('IN_IA')) {
    die( 'Access Denied' );
}
define('TM_COMMISSION_AGENT_NEW', 'commission_agent_new');
define('TM_COMMISSION_ORDER_PAY', 'commission_order_pay');
define('TM_COMMISSION_ORDER_FINISH', 'commission_order_finish');
define('TM_COMMISSION_APPLY', 'commission_apply');
define('TM_COMMISSION_CHECK', 'commission_check');
define('TM_COMMISSION_PAY', 'commission_pay');
define('TM_COMMISSION_UPGRADE', 'commission_upgrade');
define('TM_COMMISSION_BECOME', 'commission_become');
if (!class_exists('CommissionModel')) {

    class CommissionModel extends PluginModel {
        public $set = array();
        public $openid = '';

        public $member = array();
        public $allMembers = array();
        public $specialMembers = array();
        public $levelOneMembers = array();
        public $levelOneMembers_old = array();
        public $levelTwoMembers = array();
        public $levelTwoMembers_old = array();
        public $levelThrMembers = array();
        public $levelThrMembers_old = array();

        public $salesVolumes = array();
        public $salesVolumesPrice = array();
        public $salesOneVolumes = array();
        public $salesOneVolumes_old = array();
        public $salesTwoVolumes = array();
        public $salesTwoVolumes_old = array();
        public $salesThrVolumes = array();
        public $salesThrVolumes_old = array();

        public $wealths = array();
        public $wealthsPrice = array();
        public $wealthsOne = array();
        public $wealthsOne_old = array();
        public $wealthsTwo = array();
        public $wealthsTwo_old = array();
        public $wealthsThr = array();
        public $wealthsThr_old = array();

        public $afterSales = array();
        public $afterSalesAll = array();
        public $afterSalesVolumesLevel = array();

        public $records = array();

        public function getSet(){

            if(empty($this->set)){
                $set = parent::getSet();
                $set ['texts'] = array( 'agent' => empty( $set ['texts'] ['agent'] ) ? '分销商' : $set ['texts'] ['agent'], 'shop' => empty( $set ['texts'] ['shop'] ) ? '小店' : $set ['texts'] ['shop'], 'myshop' => empty( $set ['texts'] ['myshop'] ) ? '我的小店' : $set ['texts'] ['myshop'], 'center' => empty( $set ['texts'] ['center'] ) ? '分销中心' : $set ['texts'] ['center'], 'become' => empty( $set ['texts'] ['become'] ) ? '成为分销商' : $set ['texts'] ['become'], 'withdraw' => empty( $set ['texts'] ['withdraw'] ) ? '提现' : $set ['texts'] ['withdraw'], 'commission' => empty( $set ['texts'] ['commission'] ) ? '佣金' : $set ['texts'] ['commission'], 'commission1' => empty( $set ['texts'] ['commission1'] ) ? '分销佣金' : $set ['texts'] ['commission1'], 'commission_total' => empty( $set ['texts'] ['commission_total'] ) ? '累计佣金' : $set ['texts'] ['commission_total'], 'commission_ok' => empty( $set ['texts'] ['commission_ok'] ) ? '可提现佣金' : $set ['texts'] ['commission_ok'], 'commission_apply' => empty( $set ['texts'] ['commission_apply'] ) ? '已申请佣金' : $set ['texts'] ['commission_apply'], 'commission_check' => empty( $set ['texts'] ['commission_check'] ) ? '待打款佣金' : $set ['texts'] ['commission_check'], 'commission_lock' => empty( $set ['texts'] ['commission_lock'] ) ? '未结算佣金' : $set ['texts'] ['commission_lock'], 'commission_detail' => empty( $set ['texts'] ['commission_detail'] ) ? '佣金明细' : $set ['texts'] ['commission_detail'], 'order' => empty( $set ['texts'] ['order'] ) ? '分销订单' : $set ['texts'] ['order'], 'myteam' => empty( $set ['texts'] ['myteam'] ) ? '我的团队' : $set ['texts'] ['myteam'] );
                $this->set = $set;
            }

            return $this->set;
        }

        public function calculate($orderid = 0, $update = true){
            global $_W;
            $set = $this->getSet();
            $levels = $this->getLevels();
            $goods = pdo_fetchall("select og.id,og.realprice,og.total,g.hascommission, g.commission1_rate,g.commission1_pay,g.commission2_rate,g.commission2_pay,g.commission3_rate,g.commission3_pay from " . tablename('ewei_shop_order_goods') . '  og ' . ' left join ' . tablename('ewei_shop_goods') . ' g on g.id = og.goodsid' . ' where og.orderid=:orderid and og.uniacid=:uniacid', array( ':orderid' => $orderid, ':uniacid' => $_W ['uniacid'] ));
            if ($set ['level'] > 0) {
                foreach ($goods as &$cinfo) {
                    $price = $cinfo ['realprice'];
                    if ($cinfo ['hascommission'] == 1) {
                        $cinfo ['commission1'] = array( 'default' => $set ['level'] >= 1 ? $cinfo ['commission1_rate'] > 0 ? round($cinfo ['commission1_rate'] * $price / 100, 2) . "" : round($cinfo ['commission1_pay'] * $cinfo ['total'], 2) : 0 );
                        $cinfo ['commission2'] = array( 'default' => $set ['level'] >= 2 ? $cinfo ['commission2_rate'] > 0 ? round($cinfo ['commission2_rate'] * $price / 100, 2) . "" : round($cinfo ['commission2_pay'] * $cinfo ['total'], 2) : 0 );
                        $cinfo ['commission3'] = array( 'default' => $set ['level'] >= 3 ? $cinfo ['commission3_rate'] > 0 ? round($cinfo ['commission3_rate'] * $price / 100, 2) . "" : round($cinfo ['commission3_pay'] * $cinfo ['total'], 2) : 0 );
                    } else {
                        $cinfo ['commission1'] = array( 'default' => $set ['level'] >= 1 ? round($set ['commission1'] * $price / 100, 2) . "" : 0 );
                        $cinfo ['commission2'] = array( 'default' => $set ['level'] >= 2 ? round($set ['commission2'] * $price / 100, 2) . "" : 0 );
                        $cinfo ['commission3'] = array( 'default' => $set ['level'] >= 3 ? round($set ['commission3'] * $price / 100, 2) . "" : 0 );
                        foreach ($levels as $level) {
                            $cinfo ['commission1'] ['level' . $level ['id']] = $set ['level'] >= 1 ? round($level ['commission1'] * $price / 100, 2) . "" : 0;
                            $cinfo ['commission2'] ['level' . $level ['id']] = $set ['level'] >= 2 ? round($level ['commission2'] * $price / 100, 2) . "" : 0;
                            $cinfo ['commission3'] ['level' . $level ['id']] = $set ['level'] >= 3 ? round($level ['commission3'] * $price / 100, 2) . "" : 0;
                        }
                    }
                    if ($update) {
                        pdo_update('ewei_shop_order_goods', array( 'commission1' => iserializer($cinfo ['commission1']), 'commission2' => iserializer($cinfo ['commission2']), 'commission3' => iserializer($cinfo ['commission3']) ), array( 'id' => $cinfo ['id'] ));
                    }
                }
                unset( $cinfo );
            }
            return $goods;
        }

        /**
         * 连贯操作引用。
         * @param $openid
         * @return $this|bool
         */
        public function before($openid){
            if(empty($openid) && empty($this->openid)){
                return false;
            }

            if(empty($this->openid)){
                $this->openid = $openid;
            }

            if(empty($this->set)){
                $this->set = $this->getSet();
            }

            if(empty($this->member)){
                $this->member = m('member')->getMember($this->openid);
            }

            return $this;
        }

        /**
         * 获取指定用户的所有下级分销商人员信息
         * @param $openid
         * @param bool $old
         * @return $this|bool
         */
        public function getAllNextMembers($openid = '', $old = false){
            if(empty($openid) && empty($this->openid)){
                return false;
            }

            $this->before($openid);

            $memberModel = m('member');

            if($this->set['level'] >= 1){
                $this->levelOneMembers = $memberModel->getNextMembers($this->member['id'], $old);
                $this->specialMembers = $memberModel->getSpecial($this->member['id']);
            }

            if($this->set['level'] >= 2 && count($this->levelOneMembers) != 0){
                $this->levelTwoMembers = $memberModel->getNextMembers($this->_filterId($this->levelOneMembers, 'id'), $old);
            }

            if($this->set['level'] >= 3 && count($this->levelTwoMembers) != 0){
                $this->levelThrMembers = $memberModel->getNextMembers($this->_filterId($this->levelTwoMembers, 'id'), $old);
            }

            return $this;
        }

        /**
         * 获取指定用户的所有下级分销商人员信息
         * @param $openid
         * @param bool $old
         * @return $this|bool
         */
        public function getMembers(){
            $this->allMembers = array('levelOneMembers' => $this->levelOneMembers, 'levelTwoMembers' => $this->levelTwoMembers, 'levelThrMembers' => $this->levelThrMembers, 'specialMembers' => $this->specialMembers);
            return $this->allMembers;
        }

        /**
         * 获取指定用户的销售额统计
         * @param string $openid
         * @return bool
         */
        public function getAllSalesvolumes($openid = ''){
            if(empty($openid) && empty($this->openid)){
                return false;
            }

            $this->before($openid);

            $orderModel = m('order');

            if($this->set['level'] >= 1 && !empty($this->member)){
                $this->salesOneVolumes = $orderModel->getOrderByAgentid($this->member['id']);
            }

            if($this->set['level'] >= 2 && !empty($this->levelOneMembers)){
                $this->salesTwoVolumes = $orderModel->getOrderByAgentid($this->levelOneMembers);
            }

            if($this->set['level'] >= 3 && !empty($this->levelTwoMembers)){
                $this->salesThrVolumes = $orderModel->getOrderByAgentid($this->levelTwoMembers);
            }

            return $this;
        }

        /**
         * 获取统计订单
         * @return array
         */
        public function getSales(){

            $this->salesVolumes = array(
                'salesOneVolumes' => $this->salesOneVolumes,
                'salesTwoVolumes' => $this->salesTwoVolumes,
                'salesThrVolumes' => $this->salesThrVolumes,
            );

            return $this->salesVolumes;
        }

        /**
         * 获取所有财富
         * @param string $openid
         * @return $this|bool
         */
        public function getAllWealths($openid = ''){
            if(empty($openid) && empty($this->openid)){
                return false;
            }

            $this->before($openid);

            if($this->set['level'] >= 1 && !empty($this->salesOneVolumes)){

                $this->wealthsOne = $this->_wealths($this->salesOneVolumes);
            }

            if($this->set['level'] >= 2 && !empty($this->salesTwoVolumes)){
                $this->wealthsTwo = $this->_wealths($this->salesTwoVolumes);
            }

            if($this->set['level'] >= 3 && !empty($this->salesThrVolumes)){
                $this->wealthsThr = $this->_wealths($this->salesThrVolumes);
            }

            return $this;
        }

        /**
         * 获取佣金结果
         * @return array
         */
        public function getDetail(){

            $wealthsPrice = array();
            $wealthsPrice['play'] = 0;  // 已打款的佣金
            $wealthsPrice['applyed'] = 0;  // 待打款的佣金
            $wealthsPrice['apply'] = 0;  // 申请中的佣金
            $wealthsPrice['unapply'] = 0;  // 可提现的佣金
            $wealthsPrice['padding'] = 0;  // 待结算的佣金
            $wealthsPrice['invalid'] = 0;  // 被驳回的佣金

            $salesVolumesPrice = array();
            $afterSalesVolumes = array();
            $afterSalesVolumesLevel = array();

            $tempAll = array();

            if($this->set['level'] >= 1){
                $salesvolumex = $this->salesOneVolumes;

                $wealths = $this->wealthsOne;
                $members = $this->levelOneMembers;
                $temp = array();

                foreach($wealths as $wealth){

                    $order = $salesvolumex[$wealth['orderid']];

                    if($order['agentid'] == $this->member['id']){
                        $wealthsPrice = $this->_sumWealthsPrice($wealthsPrice, $order['goodsprice'], $order['status']);

                        if($order['createtime'] < $this->member['upleveltime']){
                            $level = $this->member['oldlevel'];
                        }else{
                            $level = $this->member['agentlevel'];
                        }

                        $tempAll[] = $order;
                        $order['commissionPrice'] = $this->_salesVolumesPrice($wealth['commission1'], $level);
                        $order['level'] = 1;
                        $order['agentlevel'] = $level;
                        $this->afterSalesAll[$order['id']] = $order;

                        # 迁移
                        $this->records[] = $this->_getRecord($order, $wealth, 1, $order['commissionPrice']);

                        $wealthsPrice = $this->_sumWithdrawPrice($wealthsPrice, $wealth['commission1'], $level, $order, $order['status'], $wealth['status1']);
                        $salesVolumesPrice = $this->_sumSalesVolumesPrice($salesVolumesPrice, $wealth['commission1'], $level, $order['status'] );
                        $afterSalesVolumes = $this->_pushSalesVolumes($afterSalesVolumes, $order, $order['status']);
                    }
                }

                $afterSalesVolumesLevel['level1'] = $afterSalesVolumes;
            }

            $wealths = $members = '';
            $dropOrder = $afterSalesVolumes = array();

            if($this->set['level'] >= 2){
                $salesvolumex = $this->salesTwoVolumes;

                $wealths = $this->wealthsTwo;
                $members = $this->levelOneMembers;

                foreach($wealths as $wealth){
                    $order = $salesvolumex[$wealth['orderid']];
                    $member = $members[$order['agentid']];

                    $drop = true;

                    if($member['agentid'] != 0){
                        if($member['agentid'] != 0 && $member['upleveltime'] > $order['createtime']){
                            $tsales_two[] = $order;
                        }

                        if($member['agentid'] != 0 && $member['upleveltime'] < $order['createtime']){
                            $tsales_two[] = $order;
                            $drop = false;
                        }
                    }

                    if($member['agentid'] == 0 && $member['upleveltime'] > $order['createtime']){
                        $tsales_two[] = $order;
                        $drop = false;

                    }
                    if($drop){
                        $dropOrder[] = $order;
                    }else{
                        $wealthsPrice = $this->_sumWealthsPrice($wealthsPrice, $order['goodsprice'], $order['status']);

                        if($order['createtime'] < $this->member['upleveltime']){
                            $level = $this->member['oldlevel'];
                        }else{
                            $level = $this->member['agentlevel'];
                        }

                        $tempAll[] = $order;
                        $order['commissionPrice'] = $this->_salesVolumesPrice($wealth['commission2'], $level);
                        $order['level'] = 2;
                        $order['agentlevel'] = $level;
                        $this->afterSalesAll[$order['id']] = $order;

                        # 迁移
                        $this->records[] = $this->_getRecord($order, $wealth, 2, $order['commissionPrice']);

                        $wealthsPrice = $this->_sumWithdrawPrice($wealthsPrice, $wealth['commission2'], $level, $order, $order['status'], $wealth['status2']);
                        $salesVolumesPrice = $this->_sumSalesVolumesPrice($salesVolumesPrice, $wealth['commission2'], $level, $order['status'] );
                        $afterSalesVolumes = $this->_pushSalesVolumes($afterSalesVolumes, $order, $order['status']);
                    }
                }

                $afterSalesVolumesLevel['level2'] = $afterSalesVolumes;
            }

            $wealths = $members = '';
            $dropOrder = $afterSalesVolumes = array();

            $md = 0;
            $ma = 0;
            $mg = 0;
            if($this->set['level'] >= 3){
                $salesvolumex = $this->salesThrVolumes;

                $wealths = $this->wealthsThr;
                $members = $this->levelTwoMembers;

                $i = 0;
                foreach($wealths as $wealth){
                    $i = $i+1;
                    $order = $salesvolumex[$wealth['orderid']];
                    $member = $members[$order['agentid']];
                    $ma += $order['goodsprice'];

                    if(!empty($member['agentid'])){
                        // 当前上级
                        $parentMember = $this->levelOneMembers[$member['agentid']];
                    }else if(!empty($member['oldagentid'])){
                        // 原始上级
                        $parentMember = $this->levelOneMembers[$member['oldagentid']];
                    }

                    if(!empty($parentMember['upleveltime']) && $parentMember['upleveltime'] < $order['createtime']){
                        $dropOrder[] = $order;
                        $md += $order['goodsprice'];
                        continue;
                    }

                    $drop = true;

                    if($member['agentid'] != 0){
                        if($member['agentid'] != 0 && $member['upleveltime'] > $order['createtime']){
                            $tsales_thr[] = $order;
                            $drop = false;
                        }

                        if($member['agentid'] != 0 && $member['upleveltime'] < $order['createtime']){
                            $tsales_thr[] = $order;
                            $drop = false;
                        }
                    }

                    if($member['agentid'] == 0 && $member['upleveltime'] > $order['createtime']){
                        $tsales_thr[] = $order;
                        $drop = false;
                    }

                    if($drop){
                        $dropOrder[] = $order;
                        $md += $order['goodsprice'];
                    }else{
                        $wealthsPrice = $this->_sumWealthsPrice($wealthsPrice, $order['goodsprice'], $order['status']);

                        if($order['createtime'] < $this->member['upleveltime']){
                            $level = $this->member['oldlevel'];
                        }else{
                            $level = $this->member['agentlevel'];
                        }
                        $mg += $order['goodsprice'];
                        $tempAll[] = $order;
                        $order['commissionPrice'] = $this->_salesVolumesPrice($wealth['commission3'], $level);
                        $order['level'] = 3;
                        $order['agentlevel'] = $level;
                        $this->afterSalesAll[$order['id']] = $order;

                        # 迁移
                        $this->records[] = $this->_getRecord($order, $wealth, 3, $order['commissionPrice']);

                        $wealthsPrice = $this->_sumWithdrawPrice($wealthsPrice, $wealth['commission3'], $level, $order, $order['status'], $wealth['status3']);
                        $salesVolumesPrice = $this->_sumSalesVolumesPrice($salesVolumesPrice, $wealth['commission3'], $level, $order['status'] );
                        $afterSalesVolumes = $this->_pushSalesVolumes($afterSalesVolumes, $order, $order['status']);
                    }
                }

                $afterSalesVolumesLevel['level3'] = $afterSalesVolumes;
            }

            $this->afterSalesVolumesLevel = $afterSalesVolumesLevel;
            $this->afterSales = $this->_sumAfterSales($tempAll);
            $this->wealthsPrice = $wealthsPrice;
            $this->salesVolumesPrice = $salesVolumesPrice;

            return $this;
        }

        /**
         * 获取指定用户的指定状态的佣金。
         * @param $openid // 可填写openid 或 mid
         * @param array $options // 获取佣金金额选项 ( TOTAL = 总额， OK = 可提现， LOCK = 不可提现， APPLY = 正在申请， PAY = 已支付 )
         * @return array
         */
        public function getCommissionRecordPrice($openid, $options = array()){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $set = $this->getSet();

            $time = time();
            $day_times = intval($set['settledays']) * 3600 * 24;

            $result = array();

            if (in_array('total', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` >= 3 AND `c_status` >= -1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );
                $sum = pdo_fetchcolumn($sql, $params);
                $result['total'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('ok', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` < :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['ok'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('lock', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` > :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['lock'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('apply', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['apply'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('check', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 2';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['check'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('pay', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 3';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['pay'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('invalid', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = -1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['invalid'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            return $result;
        }

        /**
         * 获取指定用户，指定状态的佣金记录。
         * @param $openid // 可填写openid 或 mid
         * @param array $options // 获取佣金金额选项 ( TOTAL = 总额， OK = 可提现， LOCK = 不可提现， APPLY = 正在申请， PAY = 已支付 )
         * @return array
         */
        public function getCommissionRecordLists($openid, $options = array()){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $set = $this->getSet();

            $time = time();
            $day_times = intval($set['settledays']) * 3600 * 24;

            $result = array();

            if (in_array('total', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` > 1 ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['total'] = pdo_fetchall($sql, $params);
            }

            if (in_array('ok', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` <= :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $result['ok'] = pdo_fetchall($sql, $params);
            }

            if (in_array('lock', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` > :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $result['lock'] = pdo_fetchall($sql, $params);
            }

            if (in_array('apply', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['apply'] = pdo_fetchall($sql, $params);
            }

            if (in_array('check', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 2';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['check'] = pdo_fetchall($sql, $params);
            }

            if (in_array('pay', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 3';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['pay'] = pdo_fetchall($sql, $params);
            }

            if (in_array('invalid', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = -1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['invalid'] = pdo_fetchall($sql, $params);
            }

            return $result;
        }

        /**
         * 获取指定状态的统计信息。
         * @param $openid // 可填写openid 或 mid
         * @param array $options // 获取佣金金额选项
         * ( TOTAL = 总额， OK = 可提现， LOCK = 不可提现， APPLY = 正在申请， PAY = 已支付 )
         * ( o_status_0 - o_status_3 分别代表订单下单 -> 完成)
         * @return array
         */
        public function getCommissionRecordStatistics($openid, $options = array()){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $set = $this->getSet();

            $time = time();
            $day_times = intval($set['settledays']) * 3600 * 24;

            $result = array();

            if (in_array('total', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` >= 1 AND `c_status` >= 0 ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['total'] = pdo_fetch($sql, $params);
            }

            if (in_array('ok', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` <= :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $result['ok'] = pdo_fetch($sql, $params);
            }

            if (in_array('lock', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` > :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $result['lock'] = pdo_fetch($sql, $params);
            }

            if (in_array('apply', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['apply'] = pdo_fetch($sql, $params);
            }

            if (in_array('check', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 2';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['check'] = pdo_fetch($sql, $params);
            }

            if (in_array('pay', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 3';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['pay'] = pdo_fetch($sql, $params);
            }

            if (in_array('invalid', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = -1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['invalid'] = pdo_fetch($sql, $params);
            }

            if (in_array('o_status_0', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 0 AND `c_status` >= 0 ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['o_status_0'] = pdo_fetch($sql, $params);
            }

            if (in_array('o_status_1', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 1 AND `c_status` >= 0';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['o_status_1'] = pdo_fetch($sql, $params);
            }

            if (in_array('o_status_2', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 2 AND `c_status` >= 0';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['o_status_2'] = pdo_fetch($sql, $params);
            }

            if (in_array('o_status_3', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` >= 0';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['o_status_3'] = pdo_fetch($sql, $params);
            }

            return $result;
        }

        public function getWealths(){
            $this->wealths = array(
                'wealthsOne' => $this->wealthsOne,
                'wealthsTwo' => $this->wealthsTwo,
                'wealthsThr' => $this->wealthsThr,
            );

            return $this->wealths;
        }

        private function _wealths($sales){
            $result = array();

            if(!empty($sales)){
                $result = m('order')->getOrderGoods(array_keys($sales));
            }

            return $result;
        }

        private function _filterId($array, $key = 'id'){
            $ids = array();

            if(is_array($array)){
                foreach($array as $val){
                    $ids[$val[$key]] = $val;
                }
            }

            return $ids;
        }

        private function _sumAfterSales($sales){

            $result = array();
            $result['finish'] = array();
            $result['finish']['price'] = 0;
            $result['finish']['count'] = 0;
            $result['send'] = array();
            $result['send']['price'] = 0;
            $result['send']['count'] = 0;
            $result['pay'] = array();
            $result['pay']['price'] = 0;
            $result['pay']['count'] = 0;
            $result['create'] = array();
            $result['create']['price'] = 0;
            $result['create']['count'] = 0;

            foreach($sales as $val){

                switch($val['status']){
                    case 3 :
                        $result['finish']['price'] += $val['goodsprice'];
                        $result['finish']['count']++;
                        break;
                    case 2 :
                        $result['send']['price'] += $val['goodsprice'];
                        $result['send']['count']++;
                        break;
                    case 1 :
                        $result['pay']['price'] += $val['goodsprice'];
                        $result['pay']['count']++;
                        break;
                    case 0 :
                        $result['create']['price'] += $val['goodsprice'];
                        $result['create']['count']++;
                        break;
                    default :
                        break;
                }

            }

            return $result;
        }

        private function _pushSalesVolumes($afterSalesVolumes, $order, $status){

            switch($status){
                case 3 :
                    $afterSalesVolumes['finish'][] = $order;
                    break;
                case 2 :
                    $afterSalesVolumes['send'][] = $order;
                    break;
                case 1 :
                    $afterSalesVolumes['pay'][] = $order;
                    break;
                case 0 :
                    $afterSalesVolumes['create'][] = $order;
                    break;
                default :
                    break;
            }

            return $afterSalesVolumes;
        }

        private function _salesVolumesPrice($commission, $level){
            $commission = iunserializer($commission);
            $price = isset( $commission['level' . $level] ) ? $commission['level' . $level] : $commission['default'];

            return $price;
        }

        private function _sumSalesVolumesPrice($salesVolumesPrice, $commission, $level, $status){
            $commission = iunserializer($commission);
            $price = isset( $commission['level' . $level] ) ? $commission['level' . $level] : $commission['default'];

            switch($status){
                case 3 :
                    $salesVolumesPrice['finish'] += $price;
                    break;
                case 2 :
                    $salesVolumesPrice['send'] += $price;
                    break;
                case 1 :
                    $salesVolumesPrice['pay'] += $price;
                    break;
                case 0 :
                    $salesVolumesPrice['create'] += $price;
                    break;
                default :
                    break;
            }

            return $salesVolumesPrice;
        }

        private function _sumWithdrawPrice($wealthsPrice, $commission, $level, $order, $ostatus, $cstatus){
            // 申请状态，-2删除，-1无效，0未申请，1申请，2审核通过 3已打款

            $commission = iunserializer($commission);
            $price = isset( $commission['level' . $level] ) ? $commission['level' . $level] : $commission['default'];

            if($ostatus == 3){
                $time = time();
                $can = false;

                $set = m('common')->getSetData();
                $set = iunserializer($set['sets']);
                $set = $set['trade'];

                if(($time - $set['refunddays'] * 24 * 60 * 60) > $order['finishtime'] ){
                    $can = true;
                }

                switch($cstatus) {
                    case 3 :
                        // 已打款
                        $wealthsPrice['play'] += $price;
                        break;
                    case 2 :
                        // 已审核
                        $wealthsPrice['applyed'] += $price;
                        break;
                    case 1 :
                        // 已申请
                        $wealthsPrice['apply'] += $price;
                        break;
                    case 0 :
                        //
                        if($can){
                            // 可提现
                            $wealthsPrice['unapply'] += $price;
                        }else{
                            // 待结算
                            $wealthsPrice['padding'] += $price;
                        }

                        break;
                    case -1 :
                        // 被驳回
                        $wealthsPrice['invalid'] += $price;
                        break;
                    default :
                        break;
                }
            }

            return $wealthsPrice;
        }

        private function _sumWealthsPrice($wealthsPrice, $price, $status){

            switch($status){
                case 3 :
                    $wealthsPrice['finish'] += $price;
                    break;
                case 2 :
                    $wealthsPrice['send'] += $price;
                    break;
                case 1 :
                    $wealthsPrice['pay'] += $price;
                    break;
                case 0 :
                    $wealthsPrice['create'] += $price;
                    break;
                default :
                    break;
            }

            return $wealthsPrice;
        }

        public function getInfox($openid, $options = null){
            global $_W;

            if (empty( $openid ) || !is_array($options)) {
                $options = array();
            }

            $member = m('member')->getMember($openid);

            $split = false;     // 佣金切割。
            if (!empty( $member['upleveltime'] )) {
                $split = true;
            }

            $set = $this->getSet();
            $level = intval($set ['level']);

            $member = m('member')->getInfo($openid);
            $agentLevel = $this->getLevel($openid);

            $payPrice = $unPayPrice = $takePrice = $finishPrice = $salesVolumePrice = $commissionsMoney = 0;
            $orderPayCount = $orderUnpayCount = $sendCount = $finishCount = 0;
            $alreadyCommissionPrice = $canCommissionPrice = $rejectCommissionPrice = $applyCommissionPrice = $commission_ok = 0;
            $agentcount = $level1 = $level2 = $level3 = 0;
            $level1_agentids = $level2_agentids = $level3_agentids = array();

            $hasCommission = $rejectCommission = $mineCommission = $adoptCommission = $applyCommission = 0;
            $level1_commissions = $level2_commissions = $level3_commissions = array();
            $beforeOrder = $afterOrder = array();
            $salesVolumes = array();
            $salesOrderPayVolumePrice = $salesOrderUnpayVolumePrice = $salesOrderSendVolumePrice = $salesOrderFinishVolumePrice = 0;

            $level1_old_agentids = $level2_old_agentids = $level3_old_agentids = array();

            $time = time();
            $day_times = intval($set ['settledays']) * 3600 * 24;

            $level1old = $level2old = $level3old = '';

            $beforeOrderx = $afterOrderx = array();

            $debug = false;

            if($_W['member']['uid'] == 15){
                $debug = true;
            }

            // 开启了一级分销
            if ($level >= 1) {
                // 销售额
                if (in_array('salesvolume', $options)) {
                    // status : -1取消状态，0普通状态，1为已付款，2为已发货，3为成功
                    $sql = 'SELECT `id`,`price`, `goodsprice`, `ordersn`,`createtime`,`finishtime`,`status` FROM ' . tablename('ewei_shop_order') . ' WHERE `uniacid` = :uniacid AND `agentid` = :agentid AND `status` >= 0 ORDER BY `createtime` DESC, `ordersn` DESC ';
                    $pam = array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] );

                    $salesVolume = pdo_fetchall($sql, $pam);

                    $salesVolumes['level1'] = $salesVolume;

                    foreach ($salesVolume as $val) {
                        $salesVolumePrice += $val['goodsprice'];

                        if ($val['status'] == 1) {
                            $orderPayCount++;
                            $salesOrderPayVolumePrice += $val['goodsprice'];
                        }

                        if ($val['status'] == 2) {
                            $sendCount++;
                            $salesOrderSendVolumePrice += $val['goodsprice'];
                        }

                        if ($val['status'] == 3) {
                            $finishCount++;
                            $salesOrderFinishVolumePrice += $val['goodsprice'];
                        }

                        if ($val['status'] == 0) {
                            $orderUnpayCount++;
                            $salesOrderUnpayVolumePrice += $val['goodsprice'];
                        }
                    }
                }

                if (in_array('ok', $options)) {
                    $level1_commissions = pdo_fetchall('select og.commission1, o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and ({$time} - o.createtime > {$day_times}) and og.status1=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));
                    foreach ($level1_commissions as $c) {
                        $commission = iunserializer($c ['commission1']);

                        if ($split && $member['upleveltime'] > $c['finishtime']) {
                            $commission_ok += isset( $commission['level' . $member['oldlevel']] ) ? $commission['level' . $member['oldlevel']] : $commission['default'];
                        } else {
                            $commission_ok += isset( $commission['level' . $member['agentlevel']] ) ? $commission['level' . $member['agentlevel']] : $commission['default'];
                        }
                    }

                }

                if (in_array('wealth', $options)) {
                    // status : -1取消状态，0普通状态，1为已付款，2为已发货，3为成功

                    $sql = 'SELECT o.id,og.commission1,og.status1,o.finishtime,o.createtime,o.paytime,o.sendtime, o.status  FROM ' . tablename('ewei_shop_order_goods') . ' AS og LEFT JOIN ' . tablename('ewei_shop_order') . ' AS o ON o.id = og.orderid WHERE o.agentid=:agentid AND o.status >= 0 AND o.uniacid=:uniacid';
                    $pam = array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member['id'] );
                    $level1_commissions = pdo_fetchall($sql, $pam);

                    foreach ($level1_commissions as $val) {
                        $commissions = iunserializer($val['commission1']);
                        //$commissionsMoney = 0;

                        if ($val['status'] == 3) {

                            if ($split && $member['upleveltime'] > $val['finishtime']) {
                                $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                            } else {
                                $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                            }

                            $finishPrice += $commissionsMoney;
                        }

                        if ($val['status'] == 2) {

                            if ($split && $member['upleveltime'] > $val['sendtime']) {
                                $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                            } else {
                                $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                            }

                            $takePrice += $commissionsMoney;
                        }

                        if ($val['status'] == 1) {

                            if ($split && $member['upleveltime'] > $val['paytime']) {
                                $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                            } else {
                                $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                            }

                            $payPrice += $commissionsMoney;
                        }

                        if ($val['status'] == 0) {

                            if ($split && $member['upleveltime'] > $val['createtime']) {
                                $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                            } else {
                                $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                            }

                            $unPayPrice += $commissionsMoney;
                        }

                        $mineCommission += $commissionsMoney;

                        // 申请状态，-2删除，-1无效，0未申请，1申请，2审核通过 3已打款
                        if (empty( $val['status1'] )) {
                            $canCommissionPrice += $commissionsMoney;
                        }
                    }
                }

                $sql = 'SELECT `id` FROM ' . tablename('ewei_shop_member') . ' WHERE `uniacid` = :uniacid AND `agentid` = :agentid AND `isagent` = 1 AND `status` = 1 ';
                $pam = array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] );
                $level1_agentids = pdo_fetchall($sql, $pam, 'id');

                $sql = 'SELECT `id`,`upleveltime` FROM ' . tablename('ewei_shop_member') . ' WHERE `uniacid` = :uniacid AND `oldagentid` = :oldagentid AND `isagent` = 1 AND `status` = 1 ';
                $pam = array( ':uniacid' => $_W ['uniacid'], ':oldagentid' => $member ['id'] );

                $level1_old_agentids = pdo_fetchall($sql, $pam, 'id');

                /*
                foreach($level1_old_agentids as $val){
                    //$level1_agentids[$val['id']] = $val;
                }
                */

                $level1 = count($level1_agentids);
                $level1old = count($level1_old_agentids);
                $agentcount += $level1;
            }

            // 开启了二级分销
            if ($level >= 2) {
                if ($level1 > 0) {

                    if (in_array('salesvolume', $options)) {
                        // status : -1取消状态，0普通状态，1为已付款，2为已发货，3为成功
                        $sql = 'SELECT `id`,`price`, `goodsprice`, `ordersn`,`createtime`,`finishtime`,`status` FROM ' . tablename('ewei_shop_order') . ' WHERE `uniacid` = :uniacid AND `agentid` in (' . implode(',', array_keys($level1_agentids)) . ') AND `status` > 0 ORDER BY `createtime` DESC , `ordersn` DESC ';
                        $pam = array( ':uniacid' => $_W['uniacid'] );
                        $salesVolume = pdo_fetchall($sql, $pam);

                        if($level1old > 0){
                            $sqlx = 'SELECT `id`,`agentid`, `price`, `goodsprice`, `ordersn`,`createtime`,`finishtime`,`status` FROM ' . tablename('ewei_shop_order') . ' WHERE `uniacid` = :uniacid AND `agentid` in (' . implode(',', array_keys($level1_old_agentids)) . ') AND `status` > 0  ORDER BY `createtime` DESC , `ordersn` DESC ';
                            $pam = array( ':uniacid' => $_W['uniacid'] );
                            $salesOldVolume = pdo_fetchall($sqlx, $pam);

                            if(!empty($salesOldVolume)){
                                foreach($salesOldVolume as $val){
                                    if($level1_old_agentids[$val['agentid']]['upleveltime'] > $val['createtime']){
                                        $salesVolume[] = $val;
                                    }
                                }
                            }
                        }

                        $salesVolumes['level2'] = $salesVolume;

                        foreach ($salesVolume as $val) {
                            $salesVolumePrice += $val['goodsprice'];

                            if ($val['status'] == 1) {
                                $orderPayCount++;
                                $salesOrderPayVolumePrice += $val['goodsprice'];
                            }

                            if ($val['status'] == 2) {
                                $sendCount++;
                                $salesOrderSendVolumePrice += $val['goodsprice'];
                            }

                            if ($val['status'] == 3) {
                                $finishCount++;
                                $salesOrderFinishVolumePrice += $val['goodsprice'];
                            }

                            if ($val['status'] == 0) {
                                $orderUnpayCount++;
                                $salesOrderUnpayVolumePrice += $val['goodsprice'];
                            }
                        }
                    }

                    if (in_array('ok', $options)) {
                        $level2_commissions = pdo_fetchall('select commission2, o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and ({$time} - o.createtime > {$day_times}) and o.status>=3 and og.status2=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));

                        if($level2old > 0){
                            $level2_old_commissions = pdo_fetchall('select commission2, o.finishtime, o.createtime, o.agentid  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_old_agentids)) . ")  and ({$time} - o.createtime > {$day_times}) and o.status>=3 and og.status2=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));

                            if(!empty($level2_old_commissions)){
                                foreach($level2_old_commissions as $val){
                                    if($level1_old_agentids[$val['agentid']]['upleveltime'] > $val['createtime']){
                                        $level2_commissions[] = $val;
                                    }
                                }
                            }
                        }

                        foreach ($level2_commissions as $c) {
                            $commission = iunserializer($c ['commission2']);

                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_ok += isset( $commission['level' . $member['oldlevel']] ) ? $commission['level' . $member['oldlevel']] : $commission['default'];
                            } else {
                                $commission_ok += isset( $commission['level' . $member['agentlevel']] ) ? $commission['level' . $member['agentlevel']] : $commission['default'];
                            }
                        }
                    }

                    if (in_array('wealth', $options)) {
                        // status : -1取消状态，0普通状态，1为已付款，2为已发货，3为成功

                        $sql = 'SELECT o.id,og.commission2,og.status1,o.finishtime,o.paytime,o.createtime,o.sendtime, o.status  FROM ' . tablename('ewei_shop_order_goods') . ' AS og LEFT JOIN ' . tablename('ewei_shop_order') . ' AS o ON o.id = og.orderid WHERE o.agentid in (' . implode(',', array_keys($level1_agentids)) . ') AND o.status >= 0 AND o.uniacid=:uniacid ';
                        $pam = array( ':uniacid' => $_W ['uniacid'] );
                        $level2_commissions = pdo_fetchall($sql, $pam);

                        if($level2old > 0){
                            $sql = 'SELECT o.id,o.agentid,og.commission2,og.status1,o.finishtime,o.paytime,o.createtime,o.sendtime, o.status  FROM ' . tablename('ewei_shop_order_goods') . ' AS og LEFT JOIN ' . tablename('ewei_shop_order') . ' AS o ON o.id = og.orderid WHERE o.agentid in (' . implode(',', array_keys($level1_old_agentids)) . ') AND o.status >= 0  AND o.uniacid=:uniacid ';
                            $pam = array( ':uniacid' => $_W ['uniacid'] );
                            $level2_old_commissions = pdo_fetchall($sql, $pam);

                            if(!empty($level2_old_commissions)){
                                foreach($level2_old_commissions as $val){
                                    if($level1_old_agentids[$val['agentid']]['upleveltime'] > $val['createtime']){
                                        $level2_commissions[] = $val;
                                    }
                                }
                            }
                        }

                        foreach ($level2_commissions as $val) {
                            $commissions = iunserializer($val['commission2']);

                            $commissionsMoney = 0;

                            if ($val['status'] == 3) {

                                if ($split && $member['upleveltime'] > $val['finishtime']) {
                                    $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                                } else {
                                    $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                                }

                                $finishPrice += $commissionsMoney;
                            }

                            if ($val['status'] == 2) {

                                if ($split && $member['upleveltime'] > $val['sendtime']) {
                                    $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                                } else {
                                    $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                                }

                                $takePrice += $commissionsMoney;
                            }

                            if ($val['status'] == 1) {

                                if ($split && $member['upleveltime'] > $val['paytime']) {
                                    $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                                } else {
                                    $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                                }

                                $payPrice += $commissionsMoney;
                            }

                            if ($val['status'] == 0) {

                                if ($split && $member['upleveltime'] > $val['createtime']) {
                                    $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                                } else {
                                    $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                                }

                                $unPayPrice += $commissionsMoney;
                            }

                            $mineCommission += $commissionsMoney;

                            // 申请状态，-2删除，-1无效，0未申请，1申请，2审核通过 3已打款
                            if (empty( $val['status2'] )) {
                                $canCommissionPrice += $commissionsMoney;
                            }
                        }
                    }

                    $sql = 'SELECT `id` FROM ' . tablename('ewei_shop_member') . ' WHERE `uniacid` = :uniacid AND `agentid` in (' . implode(',', array_keys($level1_agentids)) . ') AND `isagent` = 1 AND `status` = 1 ';
                    $pam = array( ':uniacid' => $_W ['uniacid'] );
                    $level2_agentids = pdo_fetchall($sql, $pam, 'id');

                    $sql = 'SELECT `id` FROM '.tablename('ewei_shop_member').' WHERE `uniacid` = :uniacid AND `agentid` = :agentid AND `isagent` = 1 AND `status` = 1';
                    $pam = array( ':uniacid' => $_W ['uniacid'] );

                    $level2old = 0;
                    foreach($level1_old_agentids as $val){
                        $pam[':agentid'] = $val['id'];
                        $level2_old_agentids[$val['id']] = pdo_fetchall($sql, $pam, 'id');
                        $level2old++;
                    }

                    if($debug){
                        //var_dump($level2_old_agentids);
                    }

                    $level2 = count($level2_agentids);
                    $agentcount += $level2;

                }
            }

            // 开启了三级分销
            if ($level >= 3) {
                if ($level2 > 0) {

                    if (in_array('salesvolume', $options)) {
                        // status : -1取消状态，0普通状态，1为已付款，2为已发货，3为成功
                        $sql = 'SELECT `id`,`price`, `goodsprice`, `ordersn`,`createtime`,`finishtime`,`status` FROM ' . tablename('ewei_shop_order') . ' WHERE `uniacid` = :uniacid AND `agentid` in (' . implode(',', array_keys($level2_agentids)) . ') AND `status` > 0 ORDER BY `createtime` DESC, `ordersn` DESC ';
                        $pam = array( ':uniacid' => $_W['uniacid'] );
                        $salesVolume = pdo_fetchall($sql, $pam);

                        if($level2old > 0){

                            $sqlx = 'SELECT `id`,`agentid`, `price`, `goodsprice`, `ordersn`,`createtime`,`finishtime`,`status` FROM ' . tablename('ewei_shop_order') . ' WHERE `uniacid` = :uniacid AND `agentid` in (' . implode(',', array_keys($level2_old_agentids)) . ') AND `status` > 0  ORDER BY `createtime` DESC , `ordersn` DESC ';
                            $pam = array( ':uniacid' => $_W['uniacid'] );
                            $salesOldVolume = pdo_fetchall($sqlx, $pam);

                            if(!empty($salesOldVolume)){
                                foreach($salesOldVolume as $val){
                                    foreach($level2_old_agentids as $v){
                                        if($v['id'] ==  $val['agentid'] && $v['upleveltime'] > $val['createtime']){
                                            $salesVolume[] = $val;
                                        }
                                    }
                                }
                            }
                        }

                        $salesVolumes['level3'] = $salesVolume;

                        foreach ($salesVolume as $val) {
                            $salesVolumePrice += $val['goodsprice'];

                            if ($val['status'] == 1) {
                                $orderPayCount++;
                                $salesOrderPayVolumePrice += $val['goodsprice'];
                            }

                            if ($val['status'] == 2) {
                                $sendCount++;
                                $salesOrderSendVolumePrice += $val['goodsprice'];
                            }

                            if ($val['status'] == 3) {
                                $finishCount++;
                                $salesOrderFinishVolumePrice += $val['goodsprice'];
                            }

                            if ($val['status'] == 0) {
                                $orderUnpayCount++;
                                $salesOrderUnpayVolumePrice += $val['goodsprice'];
                            }
                        }
                    }

                    if (in_array('ok', $options)) {
                        $level3_commissions = pdo_fetchall('select commission3, o.finishtime,o.id  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and ({$time} - o.createtime > {$day_times}) and o.status>=3 and og.status3=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));

                        if($level2old > 0){
                            $level3_old_commissions = pdo_fetchall('select commission3, o.finishtime, o.createtime, o.agentid  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level2_old_agentids)) . ")  and ({$time} - o.createtime > {$day_times}) and o.status>=3 and og.status2=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));

                            if(!empty($level3_old_commissions)){
                                foreach($level3_old_commissions as $val){
                                    foreach($level1_old_agentids as $v){
                                        if($v['id'] ==  $val['agentid'] && $v['upleveltime'] > $val['createtime']){
                                            $level3_commissions[] = $val;
                                        }
                                    }
                                }
                            }
                        }

                        foreach ($level3_commissions as $c) {
                            $commission = iunserializer($c ['commission3']);

                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_ok += isset( $commission['level' . $member['oldlevel']] ) ? $commission['level' . $member['oldlevel']] : $commission['default'];
                            } else {
                                $commission_ok += isset( $commission['level' . $member['agentlevel']] ) ? $commission['level' . $member['agentlevel']] : $commission['default'];
                            }
                        }

                    }

                    if (in_array('wealth', $options)) {
                        // status : -1取消状态，0普通状态，1为已付款，2为已发货，3为成功

                        $sql = 'SELECT o.id,og.commission3,og.status3,o.finishtime,o.createtime,o.paytime,o.sendtime, o.status  FROM ' . tablename('ewei_shop_order_goods') . ' AS og LEFT JOIN ' . tablename('ewei_shop_order') . ' AS o ON o.id = og.orderid WHERE o.agentid in (' . implode(',', array_keys($level2_agentids)) . ') AND o.status >= 0 AND o.uniacid=:uniacid';
                        $pam = array( ':uniacid' => $_W ['uniacid'] );
                        $level3_commissions = pdo_fetchall($sql, $pam);


                        if($level3old > 0){
                            $sql = 'SELECT o.id,o.agentid,og.commission3,og.status3,o.finishtime,o.paytime,o.createtime,o.sendtime, o.status  FROM ' . tablename('ewei_shop_order_goods') . ' AS og LEFT JOIN ' . tablename('ewei_shop_order') . ' AS o ON o.id = og.orderid WHERE o.agentid in (' . implode(',', array_keys($level2_old_agentids)) . ') AND o.status >= 0  AND o.uniacid=:uniacid ';
                            $pam = array( ':uniacid' => $_W ['uniacid'] );
                            $level3_old_commissions = pdo_fetchall($sql, $pam);

                            if(!empty($level3_old_commissions)){
                                foreach($level3_old_commissions as $val){
                                    foreach($level3_old_agentids as $v){
                                        if($v['id'] == $val['agentid'] && $v['upleveltime'] > $val['createtime'] ){
                                            $level3_commissions[] = $val;
                                        }
                                    }
                                }
                            }
                        }

                        foreach ($level3_commissions as $val) {
                            $commissions = iunserializer($val['commission3']);

                            $commissionsMoney = 0;

                            if ($val['status'] == 3) {

                                if ($split && $member['upleveltime'] > $val['finishtime']) {
                                    $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                                } else {
                                    $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                                }

                                $finishPrice += $commissionsMoney;
                            }

                            if ($val['status'] == 2) {

                                if ($split && $member['upleveltime'] > $val['sendtime']) {
                                    $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                                } else {
                                    $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                                }

                                $takePrice += $commissionsMoney;
                            }

                            if ($val['status'] == 1) {

                                if ($split && $member['upleveltime'] > $val['paytime']) {
                                    $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                                } else {
                                    $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                                }

                                $payPrice += $commissionsMoney;
                            }

                            if ($val['status'] == 0) {

                                if ($split && $member['upleveltime'] > $val['createtime']) {
                                    $commissionsMoney = isset( $commissions['level' . $member['oldlevel']] ) ? $commissions['level' . $member['oldlevel']] : $commissions['default'];
                                } else {
                                    $commissionsMoney = isset( $commissions['level' . $member['agentlevel']] ) ? $commissions['level' . $member['agentlevel']] : $commissions['default'];
                                }

                                $unPayPrice += $commissionsMoney;
                            }

                            $mineCommission += $commissionsMoney;

                            // 申请状态，-2删除，-1无效，0未申请，1申请，2审核通过 3已打款
                            if (empty( $val['status3'] )) {
                                $canCommissionPrice += $commissionsMoney;
                            }
                        }
                    }

                    $sql = 'SELECT `id` FROM ' . tablename('ewei_shop_member') . ' WHERE `uniacid` = :uniacid AND `agentid` in (' . implode(',', array_keys($level2_agentids)) . ') AND `isagent` = 1 AND `status` = 1 ';
                    $pam = array( ':uniacid' => $_W ['uniacid'] );
                    $level3_agentids = pdo_fetchall($sql, $pam, 'id');

                    /*
                    $sql = 'SELECT `id` FROM ' . tablename('ewei_shop_member') . ' WHERE `uniacid` = :uniacid AND `oldagentid` in (' . implode(',', array_keys($level2_agentids)) . ') AND `isagent` = 1 AND `status` = 1 ';
                    $pam = array( ':uniacid' => $_W ['uniacid'] );
                    $level3_old_agentids = pdo_fetchall($sql, $pam, 'id');
                    */

                    /*
                    foreach($level3_old_agentids as $val){
                        $level3_agentids[$val['id']] = $val;
                    }*/

                    $level3 = count($level3_agentids);
                    //$level3old = count($level3_old_agentids);
                    $agentcount += $level3;

                }
            }

            $result = array();

            // 我的特使
            if(in_array('special', $options)){
                $sql = 'SELECT COUNT(*) FROM '.tablename('ewei_shop_member').' WHERE `oldagentid` = :oldagentid AND `isagent` = 1 AND `uniacid` = :uniacid';
                $pam = array(':oldagentid' => $member['id'], ':uniacid'=> $_W['uniacid']);
                $result['special'] = pdo_fetchcolumn($sql, $pam);
            }

            if (in_array('salesvolume', $options)) {
                $salesVolume['salesVolumePrice'] = $salesVolumePrice;    // 销售额
                $salesVolume['salesVolumes'] = $salesVolumes;

                $salesVolume['promotion'] = array(
                    'orderUnpayCount' => $orderUnpayCount,
                    'orderPayCount' => $orderPayCount,
                    'sendCount' => $sendCount,
                    'finishCount' => $finishCount,
                    'salesOrderPayVolumePrice' => $salesOrderPayVolumePrice,
                    'salesOrderUnayVolumePrice' => $salesOrderUnpayVolumePrice,
                    'salesOrderSendVolumePrice' => $salesOrderSendVolumePrice,
                    'salesOrderFinishVolumePrice' => $salesOrderFinishVolumePrice,
                );

                $result['salesvolume'] = $salesVolume;
            }

            if (in_array('ok', $options)) {
                $result['commission_ok'] = $commission_ok;
            }

            if (in_array('wealth', $options)) {
                $sql = 'SELECT * FROM ' . tablename('ewei_shop_commission_apply') . ' WHERE `uniacid` = :uniacid AND `mid` = :mid';
                $pam = array( ':uniacid' => $_W['uniacid'], ':mid' => $member['id'] );

                $commissions = pdo_fetchall($sql, $pam);

                foreach ($commissions as $val) {
                    if ($val['status'] == 3) {
                        $hasCommission += $val['commission'];
                    }

                    if ($val['status'] == 2) {
                        $adoptCommission += $val['commission'];
                    }

                    if ($val['status'] == 1) {
                        $applyCommission += $val['commission'];
                    }

                    if ($val['status'] == -1) {
                        $rejectCommission += $val['commission'];
                    }
                }

                $wealth['applyCommission'] = array(
                    'has' => round($hasCommission, 2),          // 已完成提现财富
                    'reject' => round($rejectCommission, 2),    // 被驳回提现财富
                    'adopt' => round($adoptCommission, 2),      // 提现待打款财富
                    'apply' => round($applyCommission, 2),      // 正在申请提现的财富
                    'mine' => round($mineCommission, 2),        // 所有提现的财富
                );

                $wealth['levelCommissions'] = array( 'level1' => $level1_commissions, 'level2' => $level2_commissions, 'level3' => $level3_commissions, );

                $wealth['commissions'] = array(
                    'finishPrice' => round($finishPrice, 2),  // 所有财富
                    'takePrice' => round($takePrice, 2),      // 已经发货
                    'payPrice' => round($payPrice, 2),        // 已经支付
                    'unPayPrice' => round($unPayPrice, 2),    // 下单未支付
                    'canCommissionPrice' => round($canCommissionPrice, 2), // 可被提现财富
                );

                $result['wealth'] = $wealth;
            }

            $result['agent'] = array(
                'level1' => $level1_agentids,
                'level2' => $level2_agentids,
                'level3' => $level3_agentids,
            );

            $result['level'] = array( 'level1' => $level1, 'level2' => $level2, 'level3' => $level3, );

            $result['agentcount'] = $agentcount;    // 下线总数

            return $result;
        }

        public function getInfo($openid, $options = null){

            if (empty( $options ) || !is_array($options)) {
                $options = array();
            }
            global $_W;
            $set = $this->getSet();
            $level = intval($set ['level']);
            $member = m('member')->getInfo($openid);
            $agentLevel = $this->getLevel($openid);
            $time = time();
            $day_times = intval($set ['settledays']) * 3600 * 24;
            $agentcount = 0;
            $ordercount0 = 0;
            $ordermoney0 = 0;
            $ordercount = 0;
            $ordermoney = 0;
            $ordercount3 = 0;
            $ordermoney3 = 0;
            $commission_total = 0;
            $commission_ok = 0;
            $commission_apply = 0;
            $commission_check = 0;
            $commission_lock = 0;
            $commission_pay = 0;
            $level1 = 0;
            $level2 = 0;
            $level3 = 0;
            $order10 = 0;
            $order20 = 0;
            $order30 = 0;
            $order1 = 0;
            $order2 = 0;
            $order3 = 0;
            $order13 = 0;
            $order23 = 0;
            $order33 = 0;

            $split = false;

            if (!empty( $member['upleveltime'] )) {
                $split = true;
            }

            if ($level >= 1) {
                if (in_array('ordercount0', $options)) {
                    $level1_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid=:agentid and o.status>=0 and og.status1>=0 and o.uniacid=:uniacid  limit 1', array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));
                    $order10 += $level1_ordercount ['ordercount'];
                    $ordercount0 += $level1_ordercount ['ordercount'];
                    $ordermoney0 += $level1_ordercount ['ordermoney'];
                }
                if (in_array('ordercount', $options)) {
                    $level1_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid=:agentid and o.status>=1 and og.status1>=0 and o.uniacid=:uniacid  limit 1', array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));
                    $order1 += $level1_ordercount ['ordercount'];
                    $ordercount += $level1_ordercount ['ordercount'];
                    $ordermoney += $level1_ordercount ['ordermoney'];
                }
                if (in_array('ordercount3', $options)) {
                    $level1_ordercount3 = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid=:agentid and o.status>=3 and og.status1>=0 and o.uniacid=:uniacid  limit 1', array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));
                    $order13 += $level1_ordercount3 ['ordercount'];
                    $ordercount3 += $level1_ordercount3 ['ordercount'];
                    $ordermoney3 += $level1_ordercount3 ['ordermoney'];
                }
                if (in_array('total', $options)) {
                    $level1_commissions = pdo_fetchall('select og.commission1,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));

                    foreach ($level1_commissions as $c) {
                        $commission = iunserializer($c ['commission1']);

                        if ($split && $member['upleveltime'] > $c['finishtime']) {
                            $commission_total += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                        } else {
                            $commission_total += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                        }
                    }
                }
                if (in_array('ok', $options)) {
                    $level1_commissions = pdo_fetchall('select og.commission1,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and ({$time} - o.createtime > {$day_times}) and og.status1=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));

                    foreach ($level1_commissions as $c) {
                        $commission = iunserializer($c ['commission1']);

                        if ($split && $member['upleveltime'] > $c['finishtime']) {
                            $commission_ok += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                        } else {
                            $commission_ok += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                        }
                    }
                }
                if (in_array('lock', $options)) {
                    $level1_commissions1 = pdo_fetchall('select og.commission1,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and ({$time} - o.createtime <= {$day_times})  and og.status1=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));

                    foreach ($level1_commissions1 as $c) {
                        $commission = iunserializer($c ['commission1']);

                        if ($split && $member['upleveltime'] > $c['finishtime']) {
                            $commission_lock += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                        } else {
                            $commission_lock += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                        }
                    }
                }
                if (in_array('apply', $options)) {
                    $level1_commissions2 = pdo_fetchall('select og.commission1,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and og.status1=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));

                    foreach ($level1_commissions2 as $c) {
                        $commission = iunserializer($c ['commission1']);

                        if ($split && $member['upleveltime'] > $c['finishtime']) {
                            $commission_apply += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                        } else {
                            $commission_apply += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                        }
                    }
                }
                if (in_array('check', $options)) {
                    $level1_commissions2 = pdo_fetchall('select og.commission1,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and og.status1=2 and o.uniacid=:uniacid ", array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));

                    foreach ($level1_commissions2 as $c) {
                        $commission = iunserializer($c ['commission1']);

                        if ($split && $member['upleveltime'] > $c['finishtime']) {
                            $commission_check += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                        } else {
                            $commission_check += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                        }
                    }
                }
                if (in_array('pay', $options)) {
                    $level1_commissions2 = pdo_fetchall('select og.commission1,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and og.status1=3 and o.uniacid=:uniacid ", array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ));

                    foreach ($level1_commissions2 as $c) {
                        $commission = iunserializer($c ['commission1']);

                        if ($split && $member['upleveltime'] > $c['finishtime']) {
                            $commission_pay += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                        } else {
                            $commission_pay += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                        }
                    }
                }

                $level1_agentids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where agentid=:agentid and isagent=1 and status=1 and uniacid=:uniacid ', array( ':uniacid' => $_W ['uniacid'], ':agentid' => $member ['id'] ), 'id');
                /*$level1_old_agentids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where oldagentid=:oldagentid and isagent=1 and status=1 and uniacid=:uniacid ', array( ':uniacid' => $_W ['uniacid'], ':oldagentid' => $member ['id'] ), 'id');

                if(!empty($level1_old_agentids)){
                    foreach($level1_old_agentids as $val){
                        $level1_agentids[$val['id']] = $val;
                    }
                }*/

                $level1 = count($level1_agentids);

                $agentcount += $level1;
            }
            if ($level >= 2) {
                if ($level1 > 0) {
                    if (in_array('ordercount0', $options)) {
                        $level2_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ')  and o.status>=0 and og.status2>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'] ));
                        $order20 += $level2_ordercount ['ordercount'];
                        $ordercount0 += $level2_ordercount ['ordercount'];
                        $ordermoney0 += $level1_ordercount ['ordermoney'];
                    }
                    if (in_array('ordercount', $options)) {
                        $level2_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ')  and o.status>=1 and og.status2>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'] ));
                        $order2 += $level2_ordercount ['ordercount'];
                        $ordercount += $level2_ordercount ['ordercount'];
                        $ordermoney += $level1_ordercount ['ordermoney'];
                    }
                    if (in_array('ordercount3', $options)) {
                        $level2_ordercount3 = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ')  and o.status>=3 and og.status2>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'] ));
                        $order23 += $level2_ordercount3 ['ordercount'];
                        $ordercount3 += $level2_ordercount3 ['ordercount'];
                        $ordermoney3 += $level1_ordercount3 ['ordermoney'];
                    }
                    if (in_array('total', $options)) {
                        $level2_commissions = pdo_fetchall('select commission2,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and o.status>=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level2_commissions as $c) {
                            $commission = iunserializer($c ['commission2']);
                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_total += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_total += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('ok', $options)) {
                        $level2_commissions = pdo_fetchall('select commission2,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and ({$time} - o.createtime > {$day_times}) and o.status>=3 and og.status2=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level2_commissions as $c) {
                            $commission = iunserializer($c ['commission2']);

                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_ok += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_ok += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('lock', $options)) {
                        $level2_commissions1 = pdo_fetchall('select commission2,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and ({$time} - o.createtime <= {$day_times}) and og.status2=0 and o.status>=3  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level2_commissions1 as $c) {
                            $commission = iunserializer($c ['commission2']);

                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_lock += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_lock += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('apply', $options)) {
                        $level2_commissions2 = pdo_fetchall('select commission2,o.finishtime,o.id  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and o.status>=3 and og.status2=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level2_commissions2 as $c) {
                            $commission = iunserializer($c ['commission2']);

                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_apply += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_apply += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('check', $options)) {
                        $level2_commissions3 = pdo_fetchall('select commission2,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and o.status>=3 and og.status2=2 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level2_commissions3 as $c) {
                            $commission = iunserializer($c ['commission2']);
                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_check += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_check += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('pay', $options)) {
                        $level2_commissions3 = pdo_fetchall('select commission2,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and o.status>=3 and og.status2=3 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level2_commissions3 as $c) {
                            $commission = iunserializer($c ['commission2']);
                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_pay += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_pay += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    $level2_agentids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where agentid in( ' . implode(',', array_keys($level1_agentids)) . ') and isagent=1 and status=1 and uniacid=:uniacid', array( ':uniacid' => $_W ['uniacid'] ), 'id');
                    /*$level2_old_agentids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where oldagentid in( ' . implode(',', array_keys($level1_agentids)) . ') and isagent=1 and status=1 and uniacid=:uniacid', array( ':uniacid' => $_W ['uniacid'] ), 'id');

                    if(!empty($level2_old_agentids)){
                        foreach($level2_old_agentids as $val){
                            $level2_agentids[$val['id']] = $val;
                        }
                    }*/

                    $level2 = count($level2_agentids);
                    $agentcount += $level2;
                }
            }
            if ($level >= 3) {
                if ($level2 > 0) {
                    if (in_array('ordercount0', $options)) {
                        $level3_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct og.orderid) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ')  and o.status>=0 and og.status3>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'] ));
                        $order30 += $level3_ordercount ['ordercount'];
                        $ordercount0 += $level3_ordercount ['ordercount'];
                        $ordermoney0 += $level3_ordercount ['ordermoney'];
                    }
                    if (in_array('ordercount', $options)) {
                        $level3_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct og.orderid) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ')  and o.status>=1 and og.status3>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'] ));
                        $order3 += $level3_ordercount ['ordercount'];
                        $ordercount += $level3_ordercount ['ordercount'];
                        $ordermoney += $level3_ordercount ['ordermoney'];
                    }
                    if (in_array('ordercount3', $options)) {
                        $level3_ordercount3 = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct og.orderid) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ')  and o.status>=3 and og.status3>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'] ));
                        $order33 += $level3_ordercount3 ['ordercount'];
                        $ordercount3 += $level3_ordercount3 ['ordercount'];
                        $ordermoney3 += $level3_ordercount3 ['ordermoney'];
                    }
                    if (in_array('total', $options)) {
                        $level3_commissions = pdo_fetchall('select commission3,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level3_commissions as $c) {
                            $commission = iunserializer($c ['commission3']);

                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_total += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_total += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('ok', $options)) {
                        $level3_commissions = pdo_fetchall('select commission3,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and ({$time} - o.createtime > {$day_times}) and o.status>=3 and og.status3=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level3_commissions as $c) {
                            $commission = iunserializer($c ['commission3']);
                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_ok += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_ok += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('lock', $options)) {
                        $level3_commissions1 = pdo_fetchall('select commission3,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=3 and ({$time} - o.createtime > {$day_times}) and og.status3=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level3_commissions1 as $c) {
                            $commission = iunserializer($c ['commission3']);
                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_lock += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_lock += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('apply', $options)) {
                        $level3_commissions2 = pdo_fetchall('select commission3,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=3 and og.status3=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level3_commissions2 as $c) {
                            $commission = iunserializer($c ['commission3']);

                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_apply += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_apply += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('check', $options)) {
                        $level3_commissions3 = pdo_fetchall('select commission3,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=3 and og.status3=2 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level3_commissions3 as $c) {
                            $commission = iunserializer($c ['commission3']);
                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_check += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_check += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    if (in_array('pay', $options)) {
                        $level3_commissions3 = pdo_fetchall('select commission3,o.finishtime  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=3 and og.status3=3 and o.uniacid=:uniacid", array( ':uniacid' => $_W ['uniacid'] ));
                        foreach ($level3_commissions3 as $c) {
                            $commission = iunserializer($c ['commission3']);
                            if ($split && $member['upleveltime'] > $c['finishtime']) {
                                $commission_pay += isset( $commission ['level' . $member ['oldlevel']] ) ? $commission ['level' . $member ['oldlevel']] : $commission ['default'];
                            } else {
                                $commission_pay += isset( $commission ['level' . $agentLevel ['id']] ) ? $commission ['level' . $agentLevel ['id']] : $commission ['default'];
                            }
                        }
                    }
                    $level3_agentids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where uniacid=:uniacid and agentid in( ' . implode(',', array_keys($level2_agentids)) . ') and isagent=1 and status=1', array( ':uniacid' => $_W ['uniacid'] ), 'id');
                    /*$level3_old_agentids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where uniacid=:uniacid and oldagentid in( ' . implode(',', array_keys($level2_agentids)) . ') and isagent=1 and status=1', array( ':uniacid' => $_W ['uniacid'] ), 'id');

                    if(!empty($level3_old_agentids)){
                        foreach($level3_old_agentids as $val){
                            $level3_agentids[$val['id']] = $val;
                        }
                    }*/

                    $level3 = count($level3_agentids);
                    $agentcount += $level3;
                }
            }
            $member ['agentcount'] = $agentcount;
            $member ['ordercount'] = $ordercount;
            $member ['ordermoney'] = $ordermoney;
            $member ['order1'] = $order1;
            $member ['order2'] = $order2;
            $member ['order3'] = $order3;
            $member ['ordercount3'] = $ordercount3;
            $member ['ordermoney3'] = $ordermoney3;
            $member ['order13'] = $order13;
            $member ['order23'] = $order23;
            $member ['order33'] = $order33;
            $member ['ordercount0'] = $ordercount0;
            $member ['ordermoney0'] = $ordermoney0;
            $member ['order10'] = $order10;
            $member ['order20'] = $order20;
            $member ['order30'] = $order30;
            $member ['commission_total'] = round($commission_total, 2);
            $member ['commission_ok'] = round($commission_ok, 2);
            $member ['commission_lock'] = round($commission_lock, 2);
            $member ['commission_apply'] = round($commission_apply, 2);
            $member ['commission_check'] = round($commission_check, 2);
            $member ['commission_pay'] = round($commission_pay, 2);
            $member ['level1'] = $level1;
            $member ['level1_agentids'] = $level1_agentids;
            $member ['level2'] = $level2;
            $member ['level2_agentids'] = $level2_agentids;
            $member ['level3'] = $level3;
            $member ['level3_agentids'] = $level3_agentids;
            $member ['agenttime'] = date('Y-m-d H:i', $member ['agenttime']);
            return $member;

        }

        public function getAgents($orderid = 0){

            global $_W, $_GPC;
            $agents = array();
            $order = pdo_fetch('select id,agentid,openid from ' . tablename('ewei_shop_order') . ' where id=:id and uniacid=:uniacid limit 1', array( ':id' => $orderid, ':uniacid' => $_W ['uniacid'] ));
            if (empty( $order )) {
                return $agents;
            }
            $m1 = m('member')->getInfo($order ['agentid']);
            if (!empty( $m1 ) && $m1 ['isagent'] == 1 && $m1 ['status'] == 1) {
                $agents [] = $m1;
                if (!empty( $m1 ['agentid'] )) {
                    $m2 = m('member')->getInfo($m1 ['agentid']);
                    if (!empty( $m2 ) && $m2 ['isagent'] == 1 && $m2 ['status'] == 1) {
                        $agents [] = $m2;
                        if (!empty( $m2 ['agentid'] )) {
                            $m3 = m('member')->getInfo($m2 ['agentid']);
                            if (!empty( $m3 ) && $m3 ['isagent'] == 1 && $m3 ['status'] == 1) {
                                $agents [] = $m3;
                            }
                        }
                    }
                }
            }
            return $agents;

        }

        public function isAgent($openid){

            if (empty( $openid )) {
                return false;
            }
            if (is_array($openid)) {
                return $openid ['isagent'] == 1 && $openid ['status'] == 1;
            }
            $member = m('member')->getMember($openid);
            return $member ['isagent'] == 1 && $member ['status'] == 1;

        }

        public function getCommission($goods){

            global $_W;
            $set = $this->getSet();
            $commission = 0;
            if ($goods ['hascommission'] == 1) {
                $commission = $set ['level'] >= 1 ? $goods ['commission1_rate'] > 0 ? $goods ['commission1_rate'] * $goods ['marketprice'] / 100 : $goods ['commission1_pay'] : 0;
            } else {
                $openid = m('user')->getOpenid();
                $level = $this->getLevel($openid);
                if (!empty( $level )) {
                    $commission = $set ['level'] >= 1 ? round($level ['commission1'] * $goods ['marketprice'] / 100, 2) : 0;
                } else {
                    $commission = $set ['level'] >= 1 ? round($set ['commission1'] * $goods ['marketprice'] / 100, 2) : 0;
                }
            }
            return $commission;

        }

        public function createMyShopQrcode($mid = 0, $posterid = 0){

            global $_W;
            $path = IA_ROOT . "/addons/ewei_shop/data/qrcode/" . $_W ['uniacid'];
            if (!is_dir($path)) {
                load()->func('file');
                mkdirs($path);
            }
            $url = $_W ['siteroot'] . 'app/index.php?i=' . $_W ['uniacid'] . '&j=' . $_W ['acid'] . '&c=entry&m=ewei_shop&do=plugin&p=commission&method=myshop&mid=' . $mid;
            if (!empty( $posterid )) {
                $url .= '&posterid=' . $posterid;
            }
            $file = 'myshop_' . $posterid . '_' . $mid . '.png';
            $qr_file = $path . '/' . $file;
            if (!is_file($qr_file)) {
                require IA_ROOT . '/framework/library/qrcode/phpqrcode.php';
                QRcode::png($url, $qr_file, QR_ECLEVEL_H, 4);
            }
            return $_W ['siteroot'] . 'addons/ewei_shop/data/qrcode/' . $_W ['uniacid'] . '/' . $file;

        }

        private function createImage($url){

            load()->func('communication');
            $resp = ihttp_request($url);
            return imagecreatefromstring($resp ['content']);

        }

        public function createGoodsImage($goods, $shop_set){

            global $_W, $_GPC;
            $goods = set_medias($goods, 'thumb');
            $openid = m('user')->getOpenid();
            $me = m('member')->getInfo($openid);
            if ($me ['isagent'] == 1 && $me ['status'] == 1) {
                $userinfo = $me;
            } else {
                $mid = intval($_GPC ['mid']);
                if (!empty( $mid )) {
                    $userinfo = m('member')->getInfo($mid);
                }
            }
            $path = IA_ROOT . "/addons/ewei_shop/data/poster/" . $_W ['uniacid'] . '/';
            if (!is_dir($path)) {
                load()->func('file');
                mkdirs($path);
            }
            $img = empty( $goods ['commission_thumb'] ) ? $goods ['thumb'] : tomedia($goods ['commission_thumb']);
            $md5 = md5(json_encode(array( 'id' => $goods ['id'], 'marketprice' => $goods ['marketprice'], 'productprice' => $goods ['productprice'], 'img' => $img, 'openid' => $openid, 'version' => 4 )));
            $file = $md5 . '.jpg';
            if (!is_file($path . $file)) {
                set_time_limit(0);
                $font = IA_ROOT . "/addons/ewei_shop/static/fonts/msyh.ttf";
                $target = imagecreatetruecolor(640, 1225);
                $bg = imagecreatefromjpeg(IA_ROOT . '/addons/ewei_shop/plugin/commission/images/poster.jpg');
                imagecopy($target, $bg, 0, 0, 0, 0, 640, 1225);
                imagedestroy($bg);
                $avatar = preg_replace('/\/0$/i', '/96', $userinfo ['avatar']);
                $head = $this->createImage($avatar);
                $w = imagesx($head);
                $h = imagesy($head);
                imagecopyresized($target, $head, 24, 32, 0, 0, 88, 88, $w, $h);
                imagedestroy($head);
                $thumb = $this->createImage($img);
                $w = imagesx($thumb);
                $h = imagesy($thumb);
                imagecopyresized($target, $thumb, 0, 160, 0, 0, 640, 640, $w, $h);
                imagedestroy($thumb);
                $black = imagecreatetruecolor(640, 127);
                imagealphablending($black, false);
                imagesavealpha($black, true);
                $blackcolor = imagecolorallocatealpha($black, 0, 0, 0, 25);
                imagefill($black, 0, 0, $blackcolor);
                imagecopy($target, $black, 0, 678, 0, 0, 640, 127);
                imagedestroy($black);
                $goods_qrcode_file = tomedia(m('qrcode')->createGoodsQrcode($userinfo ['id'], $goods ['id']));
                $qrcode = $this->createImage($goods_qrcode_file);
                $w = imagesx($qrcode);
                $h = imagesy($qrcode);
                imagecopyresized($target, $qrcode, 50, 835, 0, 0, 250, 250, $w, $h);
                imagedestroy($qrcode);
                $bc = imagecolorallocate($target, 0, 3, 51);
                $cc = imagecolorallocate($target, 240, 102, 0);
                $wc = imagecolorallocate($target, 255, 255, 255);
                $yc = imagecolorallocate($target, 255, 255, 0);
                $str1 = '我是';
                imagettftext($target, 20, 0, 150, 70, $bc, $font, $str1);
                imagettftext($target, 20, 0, 210, 70, $cc, $font, $userinfo ['nickname']);
                $str2 = '我要为';
                imagettftext($target, 20, 0, 150, 105, $bc, $font, $str2);
                $str3 = $shop_set ['name'];
                imagettftext($target, 20, 0, 240, 105, $cc, $font, $str3);
                $box = imagettfbbox(20, 0, $font, $str3);
                $width = $box [4] - $box [6];
                $str4 = '代言';
                imagettftext($target, 20, 0, 240 + $width + 10, 105, $bc, $font, $str4);
                $str5 = mb_substr($goods ['title'], 0, 50, 'utf-8');
                imagettftext($target, 20, 0, 30, 730, $wc, $font, $str5);
                $str6 = "￥" . number_format($goods ['marketprice'], 2);
                imagettftext($target, 25, 0, 25, 780, $yc, $font, $str6);
                $box = imagettfbbox(26, 0, $font, $str6);
                $width = $box [4] - $box [6];
                if ($goods ['productprice'] > 0) {
                    $str7 = "￥" . number_format($goods ['productprice'], 2);
                    imagettftext($target, 22, 0, 25 + $width + 10, 780, $wc, $font, $str7);
                    $end = 25 + $width + 10;
                    $box = imagettfbbox(22, 0, $font, $str7);
                    $width = $box [4] - $box [6];
                    imageline($target, $end, 770, $end + $width + 20, 770, $wc);
                    imageline($target, $end, 771.5, $end + $width + 20, 771, $wc);
                }
                imagejpeg($target, $path . $file);
                imagedestroy($target);
            }
            return $_W ['siteroot'] . "addons/ewei_shop/data/poster/" . $_W ['uniacid'] . "/" . $file;

        }

        public function createShopImage($shop_set){

            global $_W, $_GPC;
            $shop_set = set_medias($shop_set, 'signimg');
            $path = IA_ROOT . "/addons/ewei_shop/data/poster/" . $_W ['uniacid'] . '/';
            if (!is_dir($path)) {
                load()->func('file');
                mkdirs($path);
            }
            $mid = intval($_GPC ['mid']);
            $openid = m('user')->getOpenid();
            $me = m('member')->getInfo($openid);
            if ($me ['isagent'] == 1 && $me ['status'] == 1) {
                $userinfo = $me;
            } else {
                $mid = intval($_GPC ['mid']);
                if (!empty( $mid )) {
                    $userinfo = m('member')->getInfo($mid);
                }
            }
            $md5 = md5(json_encode(array( 'openid' => $openid, 'signimg' => $shop_set ['signimg'], 'version' => 4 )));
            $file = $md5 . '.jpg';
            if (!is_file($path . $file)) {
                set_time_limit(0);
                @ini_set('memory_limit', '256M');
                $font = IA_ROOT . "/addons/ewei_shop/static/fonts/msyh.ttf";
                $target = imagecreatetruecolor(640, 1225);
                $bc = imagecolorallocate($target, 0, 3, 51);
                $cc = imagecolorallocate($target, 240, 102, 0);
                $wc = imagecolorallocate($target, 255, 255, 255);
                $yc = imagecolorallocate($target, 255, 255, 0);
                $bg = imagecreatefromjpeg(IA_ROOT . '/addons/ewei_shop/plugin/commission/images/poster.jpg');
                imagecopy($target, $bg, 0, 0, 0, 0, 640, 1225);
                imagedestroy($bg);
                $avatar = preg_replace('/\/0$/i', '/96', $userinfo ['avatar']);
                $head = $this->createImage($avatar);
                $w = imagesx($head);
                $h = imagesy($head);
                imagecopyresized($target, $head, 24, 32, 0, 0, 88, 88, $w, $h);
                imagedestroy($head);
                $thumb = $this->createImage($shop_set ['signimg']);
                $w = imagesx($thumb);
                $h = imagesy($thumb);
                imagecopyresized($target, $thumb, 0, 160, 0, 0, 640, 640, $w, $h);
                imagedestroy($thumb);
                $qrcode_file = tomedia($this->createMyShopQrcode($userinfo ['id']));
                $qrcode = $this->createImage($qrcode_file);
                $w = imagesx($qrcode);
                $h = imagesy($qrcode);
                imagecopyresized($target, $qrcode, 50, 835, 0, 0, 250, 250, $w, $h);
                imagedestroy($qrcode);
                $str1 = '我是';
                imagettftext($target, 20, 0, 150, 70, $bc, $font, $str1);
                imagettftext($target, 20, 0, 210, 70, $cc, $font, $userinfo ['nickname']);
                $str2 = '我要为';
                imagettftext($target, 20, 0, 150, 105, $bc, $font, $str2);
                $str3 = $shop_set ['name'];
                imagettftext($target, 20, 0, 240, 105, $cc, $font, $str3);
                $box = imagettfbbox(20, 0, $font, $str3);
                $width = $box [4] - $box [6];
                $str4 = '代言';
                imagettftext($target, 20, 0, 240 + $width + 10, 105, $bc, $font, $str4);
                imagejpeg($target, $path . $file);
                imagedestroy($target);
            }
            return $_W ['siteroot'] . "addons/ewei_shop/data/poster/" . $_W ['uniacid'] . "/" . $file;

        }

        public function checkAgent(){

            global $_W, $_GPC;
            $set = $this->getSet();
            if (empty( $set ['level'] )) {
                return;
            }
            $openid = m('user')->getOpenid();
            if (empty( $openid )) {
                return;
            }
            $member = m('member')->getMember($openid);
            if (empty( $member )) {
                return;
            }
            $parent = false;
            $mid = intval($_GPC ['mid']);
            if (!empty( $mid )) {
                $parent = m('member')->getMember($mid);
            }
            $parent_is_agent = !empty( $parent ) && $parent ['isagent'] == 1 && $parent ['status'] == 1;
            if ($parent_is_agent) {
                if ($parent ['openid'] != $openid) {
                    $clickcount = pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_commission_clickcount') . ' where uniacid=:uniacid and openid=:openid and from_openid=:from_openid limit 1', array( ':uniacid' => $_W ['uniacid'], ':openid' => $openid, ':from_openid' => $parent ['openid'] ));
                    if ($clickcount <= 0) {
                        $click = array( 'uniacid' => $_W ['uniacid'], 'openid' => $openid, 'from_openid' => $parent ['openid'], 'clicktime' => time() );
                        pdo_insert('ewei_shop_commission_clickcount', $click);
                        pdo_update('ewei_shop_member', array( 'clickcount' => $parent ['clickcount'] + 1 ), array( 'uniacid' => $_W ['uniacid'], 'id' => $parent ['id'] ));
                    }
                }
            }
            if ($this->isAgent($openid)) {
                return;
            }

            /*
            if ($type == 0) {
                $first = pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_member') . ' where id<:id and uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'], ':id' => $member ['id'] ));
                if ($first <= 0) {
                    pdo_update('ewei_shop_member', array( 'isagent' => 1, 'status' => 1, 'agenttime' => time() ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));
                    return;
                }
            }
            */

            $time = time();
            $become_child = intval($set ['become_child']);
            if ($parent_is_agent) {
                if (empty( $become_child )) {
                    if (empty( $member ['agentid'] ) && $member ['id'] != $parent ['id']) {
                        pdo_update('ewei_shop_member', array( 'agentid' => $parent ['id'], 'childtime' => $time ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));
                        $this->sendMessage($parent ['openid'], array( 'nickname' => $member ['nickname'], 'childtime' => $time ), TM_COMMISSION_AGENT_NEW);
                    }
                } else {
                    if (empty( $member ['agentid'] ) && $member ['id'] != $parent ['id']) {
                        pdo_update('ewei_shop_member', array( 'inviter' => $parent ['id'] ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));
                    }
                }
            }
            $become_check = intval($set ['become_check']);
            if (empty( $set ['become'] )) {
                if ($parent_is_agent) {
                    pdo_update('ewei_shop_member', array( 'isagent' => 1, 'status' => $become_check, 'agenttime' => $become_check == 1 ? $time : 0 ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));
                    if ($become_check == 1) {
                        $this->sendMessage($openid, array( 'nickname' => $member ['nickname'], 'agenttime' => $time ), TM_COMMISSION_BECOME);
                    }
                }
            }

        }

        public function checkOrderConfirm($orderid = '0'){

            global $_W, $_GPC;
            if (empty( $orderid )) {
                return;
            }
            $set = $this->getSet();
            if (empty( $set ['level'] )) {
                return;
            }
            $order = pdo_fetch('select id,openid,ordersn,goodsprice,agentid,paytime from ' . tablename('ewei_shop_order') . ' where id=:id and status>=0 and uniacid=:uniacid limit 1', array( ':id' => $orderid, ':uniacid' => $_W ['uniacid'] ));
            if (empty( $order )) {
                return;
            }
            $openid = $order ['openid'];
            $member = m('member')->getMember($openid);
            if (empty( $member )) {
                return;
            }
            $become_child = intval($set ['become_child']);
            $parent = false;
            if (empty( $become_child )) {
                $parent = m('member')->getMember($member ['agentid']);
            } else {
                $parent = m('member')->getMember($member ['inviter']);
            }
            $parent_is_agent = !empty( $parent ) && $parent ['isagent'] == 1 && $parent ['status'] == 1;
            $time = time();
            $become_child = intval($set ['become_child']);
            if ($parent_is_agent) {
                if ($become_child == 1) {
                    if (empty( $member ['agentid'] ) && $member ['id'] != $parent ['id']) {
                        $member ['agentid'] = $parent ['id'];
                        pdo_update('ewei_shop_member', array( 'agentid' => $parent ['id'], 'childtime' => $time ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));
                        $this->sendMessage($parent ['openid'], array( 'nickname' => $member ['nickname'], 'childtime' => $time ), TM_COMMISSION_AGENT_NEW);
                    }
                }
            }
            /*
             * if (!empty($member['agentid'])) {
             * pdo_update('ewei_shop_order', array('agentid' => $member['agentid']), array('id' => $orderid));
             * }
             */
            $isagent = $member ['isagent'] == 1 && $member ['status'] == 1;
            // 如果是代理，不管在任何地方消费那都算自己是一级
            if ($isagent) {
                pdo_update('ewei_shop_order', array( 'agentid' => $parent ['id'] ), array( 'id' => $orderid ));
            } else if ($parent_is_agent) {
                pdo_update('ewei_shop_order', array( 'agentid' => $parent ['id'] ), array( 'id' => $orderid ));
            }

        }

        public function checkOrderPay($orderid = '0'){

            global $_W, $_GPC;
            if (empty( $orderid )) {
                return;
            }

            $set = $this->getSet();
            if (empty( $set ['level'] )) {
                return;
            }
            $order = pdo_fetch('select id,openid,ordersn,goodsprice,agentid,paytime from ' . tablename('ewei_shop_order') . ' where id=:id and status>=1 and uniacid=:uniacid limit 1', array( ':id' => $orderid, ':uniacid' => $_W ['uniacid'] ));
            if (empty( $order )) {
                return;
            }
            $openid = $order ['openid'];
            $member = m('member')->getMember($openid);
            if (empty( $member )) {
                return;
            }

            // 添加初次订单识别
            $sql = 'SELECT count(*) FROM '.tablename('ewei_shop_order').' WHERE `openid` = :openid AND `uniacid` = :uniacid';
            $pam = array(':openid' => $member['openid'], ':uniacid' => $_W['uniacid']);
            $count = pdo_fetchcolumn($sql, $pam);
            if($count == 1){
                pdo_update('ewei_shop_order', array('firstorder' => 1), array('id' => $orderid));
            }

            $become_child = intval($set ['become_child']);
            $parent = false;
            if (empty( $become_child )) {
                $parent = m('member')->getMember($member ['agentid']);
            } else {
                $parent = m('member')->getMember($member ['inviter']);
            }
            $parent_is_agent = !empty( $parent ) && $parent ['isagent'] == 1 && $parent ['status'] == 1;
            $time = time();
            $become_child = intval($set ['become_child']);
            if ($parent_is_agent) {
                if ($become_child == 2) {
                    if (empty( $member ['agentid'] ) && $member ['id'] != $parent ['id']) {
                        $member ['agentid'] = $parent ['id'];
                        pdo_update('ewei_shop_member', array( 'agentid' => $parent ['id'], 'childtime' => $time ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));
                        $this->sendMessage($parent ['openid'], array( 'nickname' => $member ['nickname'], 'childtime' => $time ), TM_COMMISSION_AGENT_NEW);
                        if (empty( $order ['agentid'] )) {
                            $order ['agentid'] = $parent ['id'];
                            pdo_update('ewei_shop_order', array( 'agentid' => $parent ['id'] ), array( 'id' => $orderid ));
                        }
                    }
                }
            }
            $isagent = $member ['isagent'] == 1 && $member ['status'] == 1;
            if (!$isagent && empty( $set ['become_order'] )) {
                $time = time();
                if ($set ['become'] == 2 || $set ['become'] == 3) {
                    if (!empty( $member ['agentid'] )) {
                        $parent = m('member')->getMember($member ['agentid']);
                        if (empty( $parent ) || $parent ['isagent'] != 1 || $parent ['status'] != 1) {
                            return;
                        }
                    }
                    $can = false;
                    if ($set ['become'] == '2') {
                        $ordercount = pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_order') . ' where openid=:openid and status>=1 and uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'], ':openid' => $openid ));
                        $can = $ordercount >= intval($set ['become_ordercount']);
                    } else {
                        if ($set ['become'] == '3') {
                            $moneycount = pdo_fetchcolumn('select sum(og.realprice) from ' . tablename('ewei_shop_order_goods') . ' og left join ' . tablename('ewei_shop_order') . ' o on og.orderid=o.id  where o.openid=:openid and o.status>=1 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'], ':openid' => $openid ));
                            $can = $moneycount >= floatval($set ['become_moneycount']);
                        }
                    }
                    if ($can) {
                        $become_check = intval($set ['become_check']);
                        pdo_update('ewei_shop_member', array( 'status' => 1, 'isagent' => $become_check, 'agenttime' => $time ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));
                        if ($become_check == 1) {
                            $this->sendMessage($openid, array( 'nickname' => $member ['nickname'], 'agenttime' => $time ), TM_COMMISSION_BECOME);
                        }
                    }
                }
            }
            if (!empty( $member ['agentid'] )) {
                $parent = m('member')->getMember($member ['agentid']);
                if (empty( $parent ) || $parent ['isagent'] != 1 || $parent ['status'] != 1) {
                    return;
                }
                if ($order ['agentid'] != $parent ['id']) {
                    return;
                }
                $countPrice = 0;
                $countPriceLists = $this->_getCountPriceByOrderId($orderid, $set ['level']);

                if (!empty( $countPriceLists )) {
                    $split = false;

                    if (!empty( $parent['oldlevel'] )) {
                        $split = true;
                    }

                    foreach ($countPriceLists as $key => $val) {
                        $commission = iunserializer($val['commission1']);

                        if ($split && $parent['upleveltime'] > $order['paytime']) {
                            $commissionsMoney = isset( $commission['level' . $parent['oldlevel']] ) ? $commission['level' . $parent['oldlevel']] : $commission['default'];
                        } else {
                            $commissionsMoney = isset( $commission['level' . $parent['agentlevel']] ) ? $commission['level' . $parent['agentlevel']] : $commission['default'];
                        }

                        $countPrice += $commissionsMoney;
                    }
                }

                $this->sendMessage($parent ['openid'], array( 'nickname' => $member ['nickname'], 'ordersn' => $order ['ordersn'], 'price' => $order ['goodsprice'], 'countPrice' => $countPrice, 'paytime' => $order ['paytime'] ), TM_COMMISSION_ORDER_PAY);
            }

        }

        public function checkOrderFinish($orderid = ''){

            global $_W, $_GPC;
            if (empty( $orderid )) {
                return;
            }
            $order = pdo_fetch('select id,openid, ordersn,goodsprice,agentid,finishtime from ' . tablename('ewei_shop_order') . ' where id=:id and status>=3 and uniacid=:uniacid limit 1', array( ':id' => $orderid, ':uniacid' => $_W ['uniacid'] ));
            if (empty( $order )) {
                return;
            }
            $set = $this->getSet();
            if (empty( $set ['level'] )) {
                return;
            }
            $openid = $order ['openid'];
            $member = m('member')->getMember($openid);
            if (empty( $member )) {
                return;
            }
            $time = time();
            $isagent = $member ['isagent'] == 1 && $member ['status'] == 1;

            if (!$isagent && $set ['become_order'] == 1) {
                if ($set ['become'] == 2 || $set ['become'] == 3) {
                    if (!empty( $member ['agentid'] )) {
                        $parent = m('member')->getMember($member ['agentid']);
                        if (empty( $parent ) || $parent ['isagent'] != 1 || $parent ['status'] != 1) {
                            return;
                        }
                    }
                    $can = false;
                    if ($set ['become'] == '2') {
                        $ordercount = pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_order') . ' where openid=:openid and status>=3 and uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'], ':openid' => $openid ));
                        $can = $ordercount >= intval($set ['become_ordercount']);
                    } else {
                        if ($set ['become'] == '3') {
                            $moneycount = pdo_fetchcolumn('select sum(goodsprice) from ' . tablename('ewei_shop_order') . ' where openid=:openid and status>=3 and uniacid=:uniacid limit 1', array( ':uniacid' => $_W ['uniacid'], ':openid' => $openid ));
                            $can = $moneycount >= floatval($set ['become_moneycount']);
                        }
                    }
                    if ($can) {
                        $become_check = intval($set ['become_check']);
                        pdo_update('ewei_shop_member', array( 'status' => 1, 'isagent' => $become_check, 'agenttime' => $time ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));
                        if ($become_check == 1) {
                            $this->sendMessage($member ['openid'], array( 'nickname' => $member ['nickname'], 'agenttime' => $time ), TM_COMMISSION_BECOME);
                        }
                    }
                }
            }

            $member = m('member')->getMember($openid);
            $isagent = $member ['isagent'] == 1 && $member ['status'] == 1;

            if ($isagent) {
                $this->upgradeLevel($openid, $orderid);
            }

            if (!empty( $member ['agentid'] )) {
                $parent = m('member')->getMember($member ['agentid']);
                if (empty( $parent ) || $parent ['isagent'] != 1 || $parent ['status'] != 1) {
                    return;
                }
                if ($order ['agentid'] != $parent ['id']) {
                    return;
                }
                $this->sendMessage($parent ['openid'], array( 'nickname' => $member ['nickname'], 'ordersn' => $order ['ordersn'], 'price' => $order ['goodsprice'], 'finishtime' => $order ['finishtime'] ), TM_COMMISSION_ORDER_FINISH);
            }

        }

        function getShop($m){

            global $_W;
            $member = m('member')->getMember($m);
            $shop = pdo_fetch('select * from ' . tablename('ewei_shop_commission_shop') . ' where uniacid=:uniacid and mid=:mid limit 1', array( ':uniacid' => $_W ['uniacid'], ':mid' => $member ['id'] ));
            $sysset = m('common')->getSysset(array( 'shop', 'share' ));
            $set = $sysset ['shop'];
            $share = $sysset ['share'];
            $desc = $share ['desc'];
            if (empty( $desc )) {
                $desc = $set ['description'];
            }
            if (empty( $desc )) {
                $desc = $set ['name'];
            }
            if (empty( $shop )) {
                $shop = array( 'name' => $member ['nickname'] . '的小店', 'logo' => $member ['avatar'], 'desc' => $desc, 'img' => tomedia($set ['img']) );
            } else {
                if (empty( $shop ['name'] )) {
                    $shop ['name'] = $member ['nickname'] . '的小店';
                }
                if (empty( $shop ['logo'] )) {
                    $shop ['logo'] = tomedia($member ['avatar']);
                }
                if (empty( $shop ['img'] )) {
                    $shop ['img'] = tomedia($set ['img']);
                }
                if (empty( $shop ['desc'] )) {
                    $shop ['desc'] = $desc;
                }
            }
            return $shop;

        }

        function getLevels($all = true){

            global $_W;
            if ($all) {
                return pdo_fetchall('select * from ' . tablename('ewei_shop_commission_level') . ' where uniacid=:uniacid order by commission1 asc', array( ':uniacid' => $_W ['uniacid'] ));
            } else {
                return pdo_fetchall('select * from ' . tablename('ewei_shop_commission_level') . ' where uniacid=:uniacid and (ordermoney>0 or commissionmoney>0) order by commission1 asc', array( ':uniacid' => $_W ['uniacid'] ));
            }

        }

        function getLevel($openid){

            global $_W;
            if (empty( $openid )) {
                return false;
            }
            $member = m('member')->getMember($openid);
            if (empty( $member ['agentlevel'] )) {
                return false;
            }
            $level = pdo_fetch('select * from ' . tablename('ewei_shop_commission_level') . ' where uniacid=:uniacid and id=:id limit 1', array( ':uniacid' => $_W ['uniacid'], ':id' => $member ['agentlevel'] ));
            return $level;

        }

        function upgradeLevel($openid, $orderid = 0){

            global $_W;
            if (empty( $openid )) {
                return;
            }
            $set = $this->getSet();
            if (empty( $set ['level'] )) {
                return;
            }
            $m = m('member')->getMember($openid);
            $agents = array();

            $time = time() + 60;

            $m1 = $m2 = $m3 = '';

            if (!empty( $m )) {
                if (!empty( $m ['agentid'] )) {
                    $m1 = m('member')->getMember($m['agentid']);
                    if (!empty( $m1 )) {
                        $agents[] = $m1;
                        if (!empty( $m1 ['agentid'] ) && $m1 ['isagent'] == 1 && $m1 ['status'] == 1) {
                            $m2 = m('member')->getMember($m1 ['agentid']);
                            if (!empty( $m2 ) && $m2 ['isagent'] == 1 && $m2 ['status'] == 1) {
                                $agents[] = $m2;
                                if (!empty( $m2 ['agentid'] ) && $m2 ['isagent'] == 1 && $m2 ['status'] == 1) {
                                    $m3 = m('member')->getMember($m2 ['agentid']);
                                    if (!empty( $m3 ) && $m3 ['isagent'] == 1 && $m3 ['status'] == 1) {
                                        $agents[] = $m3;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            $orderModel = m('order');
            $mLevel = $this->getLevel($openid);
            $aLevel = $this->getLevel($m1['openid']);

            // 指定用户订单总额与对应等级。
            $allAmount = $orderModel->getAllAmount($openid);
            $allAmountLevels = $this->getCustomLevel($allAmount);

            $dodo = false;

            if ($allAmountLevels['c']['levelname'] == '环保特使') {
                $dodo = true;
            }

            if (isset( $allAmountLevels['c'] ) && $allAmountLevels['c']['id'] != $m['agentlevel']) {
                $do = true;

                if (!empty( $mLevel )) {
                    $do = $mLevel['ordermoney'] >= $allAmountLevels['c']['ordermoney'] ? false : true;
                }

                if ($do) {
                    // 是否升级上级。
                    if ($dodo) {

                        pdo_update('ewei_shop_member', array( 'agentid' => 0, 'oldagentid'=> $m['agentid'], 'agentlevel' => $allAmountLevels['c']['id'], 'upleveltime' => $time, 'oldlevel' => $mLevel['id'] ), array( 'id' => $m['id'] ));

                        if (!empty( $aLevel )) {
                            $do = $aLevel['ordermoney'] >= $allAmountLevels['c']['ordermoney'] ? false : true;
                        }

                        if ($do) {
                            pdo_update('ewei_shop_member', array( 'agentid' => 0, 'oldagentid'=> $m1['agentid'], 'agentlevel' => $allAmountLevels['c']['id'], 'upleveltime' => $time, 'oldlevel' => $aLevel['id'] ), array( 'id' => $m1['id'] ));
                            $this->sendMessage($m1['openid'], array( 'nickname' => $m1['nickname'], 'oldlevel' => $aLevel, 'newlevel' => $allAmountLevels['c'] ), TM_COMMISSION_UPGRADE);
                            m('member')->upgradeLevel2($m1['openid'], $allAmountLevels['m']);
                        }

                    } else {
                        pdo_update('ewei_shop_member', array( 'agentlevel' => $allAmountLevels['c']['id'] ), array( 'id' => $m['id'] ));
                    }

                    $this->sendMessage($m['openid'], array( 'nickname' => $m['nickname'], 'oldlevel' => $mLevel, 'newlevel' => $allAmountLevels['c'] ), TM_COMMISSION_UPGRADE);
                    m('member')->upgradeLevel2($m['openid'], $allAmountLevels['m']);
                }
            }

            // 同级的订单总额与对应等级。
            if(!empty($m['agentid']) && !empty($m) && $aLevel['levelname'] != '环保特使'){
                $superiorAgents = $this->getNextAgents($m['agentid']);
                $superiorAmount = 0;

                if(!empty($superiorAgents)){
                    foreach ($superiorAgents as $val) {
                        $superiorAmount += $orderModel->getAllAmount($val['openid']);
                    }
                }

                $superiorAmountLevel = $this->getCustomLevel($superiorAmount);

                $do = false;

                if (!empty( $aLevel )) {
                    $do = $aLevel['ordermoney'] >= $superiorAmountLevel['c']['ordermoney'] ? false : true;
                }

                if(!empty($do)){
                    if ($superiorAmountLevel['c']['levelname'] == '环保特使') {
                        pdo_update('ewei_shop_member', array( 'agentid' => 0, 'oldagentid'=> $m1['agentid'], 'agentlevel' => $superiorAmountLevel['c']['id'], 'upleveltime' => $time, 'oldlevel' => $aLevel['id'] ), array( 'id' => $m1['id'] ));
                        $this->sendMessage($m1['openid'], array( 'nickname' => $m1['nickname'], 'oldlevel' => $aLevel, 'newlevel' => $superiorAmountLevel['c'] ), TM_COMMISSION_UPGRADE);
                        m('member')->upgradeLevel2($m1['openid'], $superiorAmountLevel['m']);
                    }
                }
            }

            return true;
        }

        /**
         * 根据金额，获取对应等级
         * @param $amount
         * @return array
         */
        public function getCustomLevel($amount){
            global $_W;

            $sql = 'select * from ' . tablename('ewei_shop_commission_level') . ' where uniacid=:uniacid ' . ' and :amount >= ordermoney and ordermoney > 0  order by ordermoney desc LIMIT 1';
            $pam = array( ':uniacid' => $_W ['uniacid'], ':amount' => $amount );
            $commissionLevel = pdo_fetch($sql, $pam);

            $sql = 'select * from ' . tablename('ewei_shop_member_level') . ' where uniacid=:uniacid ' . ' and :amount >= ordermoney and ordermoney > 0  order by ordermoney desc LIMIT 1';
            $pam = array( ':uniacid' => $_W ['uniacid'], ':amount' => $amount );
            $memberLevel = pdo_fetch($sql, $pam);

            return array( 'c' => $commissionLevel, 'm' => $memberLevel );
        }

        function getNextAgents($mid){
            global $_W;

            $sql = 'SELECT `id`,`openid` FROM ' . tablename('ewei_shop_member') . ' WHERE `uniacid` = :uniacid AND `agentid` = :agentid AND `status` = 1';
            $parm = array( ':uniacid' => $_W['uniacid'], ':agentid' => $mid );

            return pdo_fetchall($sql, $parm);
        }

        function sendMessage($openid = '', $data = array(), $message_type = ''){

            global $_W, $_GPC;
            $set = $this->getSet();
            $tm = $set ['tm'];
            $templateid = $tm ['templateid'];
            $member = m('member')->getMember($openid);
            $usernotice = unserialize($member ['noticeset']);
            if (!is_array($usernotice)) {
                $usernotice = array();
            }
            if ($message_type == TM_COMMISSION_AGENT_NEW && !empty( $tm ['commission_agent_new'] ) && empty( $usernotice ['commission_agent_new'] )) {
                $message = $tm ['commission_agent_new'];
                $message = str_replace('[昵称]', $data ['nickname'], $message);
                $message = str_replace('[时间]', date('Y-m-d H:i:s', $data ['childtime']), $message);
                $msg = array( 'keyword1' => array( 'value' => !empty( $tm ['commission_agent_newtitle'] ) ? $tm ['commission_agent_newtitle'] : '新增下线通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                if (!empty( $templateid )) {
                    m('message')->sendTplNotice($openid, $templateid, $msg);
                } else {
                    m('message')->sendCustomNotice($openid, $msg);
                }
            } else {
                if ($message_type == TM_COMMISSION_ORDER_PAY && !empty( $tm ['commission_order_pay'] ) && empty( $usernotice ['commission_order_pay'] )) {
                    $message = $tm ['commission_order_pay'];
                    $message = str_replace('[昵称]', $data ['nickname'], $message);
                    $message = str_replace('[时间]', date('Y-m-d H:i:s', $data ['paytime']), $message);
                    $message = str_replace('[订单编号]', $data ['ordersn'], $message);
                    $message = str_replace('[订单金额]', $data ['price'], $message);
                    $message = str_replace('[佣金]', $data ['countPrice'], $message);
                    $msg = array( 'keyword1' => array( 'value' => !empty( $tm ['commission_order_paytitle'] ) ? $tm ['commission_order_paytitle'] : '下线付款通知' ), 'keyword2' => array( 'value' => $message ) );
                    if (!empty( $templateid )) {
                        m('message')->sendTplNotice($openid, $templateid, $msg);
                    } else {
                        m('message')->sendCustomNotice($openid, $msg);
                    }
                } else {
                    if ($message_type == TM_COMMISSION_ORDER_FINISH && !empty( $tm ['commission_order_finish'] ) && empty( $usernotice ['commission_order_finish'] )) {
                        $message = $tm ['commission_order_finish'];
                        $message = str_replace('[昵称]', $data ['nickname'], $message);
                        $message = str_replace('[时间]', date('Y-m-d H:i:s', $data ['finishtime']), $message);
                        $message = str_replace('[订单编号]', $data ['ordersn'], $message);
                        $message = str_replace('[订单金额]', $data ['price'], $message);
                        $msg = array( 'keyword1' => array( 'value' => !empty( $tm ['commission_order_finishtitle'] ) ? $tm ['commission_order_finishtitle'] : '下线确认收货通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                        if (!empty( $templateid )) {
                            m('message')->sendTplNotice($openid, $templateid, $msg);
                        } else {
                            m('message')->sendCustomNotice($openid, $msg);
                        }
                    } else {
                        if ($message_type == TM_COMMISSION_APPLY && !empty( $tm ['commission_apply'] ) && empty( $usernotice ['commission_apply'] )) {
                            $message = $tm ['commission_apply'];
                            $message = str_replace('[昵称]', $member ['nickname'], $message);
                            $message = str_replace('[时间]', date('Y-m-d H:i:s', time()), $message);
                            $message = str_replace('[金额]', $data ['commission'], $message);
                            $message = str_replace('[提现方式]', $data ['type'], $message);
                            $msg = array( 'keyword1' => array( 'value' => !empty( $tm ['commission_applytitle'] ) ? $tm ['commission_applytitle'] : '提现申请提交成功', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                            if (!empty( $templateid )) {
                                m('message')->sendTplNotice($openid, $templateid, $msg);
                            } else {
                                m('message')->sendCustomNotice($openid, $msg);
                            }
                        } else {
                            if ($message_type == TM_COMMISSION_CHECK && !empty( $tm ['commission_check'] ) && empty( $usernotice ['commission_check'] )) {
                                $message = $tm ['commission_check'];
                                $message = str_replace('[昵称]', $member ['nickname'], $message);
                                $message = str_replace('[时间]', date('Y-m-d H:i:s', time()), $message);
                                $message = str_replace('[金额]', $data ['commission'], $message);
                                $message = str_replace('[提现方式]', $data ['type'], $message);
                                $msg = array( 'keyword1' => array( 'value' => !empty( $tm ['commission_checktitle'] ) ? $tm ['commission_checktitle'] : '提现申请审核处理完成', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                                if (!empty( $templateid )) {
                                    m('message')->sendTplNotice($openid, $templateid, $msg);
                                } else {
                                    m('message')->sendCustomNotice($openid, $msg);
                                }
                            } else {
                                if ($message_type == TM_COMMISSION_PAY && !empty( $tm ['commission_pay'] ) && empty( $usernotice ['commission_pay'] )) {
                                    $message = $tm ['commission_pay'];
                                    $message = str_replace('[昵称]', $member ['nickname'], $message);
                                    $message = str_replace('[时间]', date('Y-m-d H:i:s', time()), $message);
                                    $message = str_replace('[金额]', $data ['commission'], $message);
                                    $message = str_replace('[提现方式]', $data ['type'], $message);
                                    $msg = array( 'keyword1' => array( 'value' => !empty( $tm ['commission_paytitle'] ) ? $tm ['commission_paytitle'] : '佣金打款通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                                    if (!empty( $templateid )) {
                                        m('message')->sendTplNotice($openid, $templateid, $msg);
                                    } else {
                                        m('message')->sendCustomNotice($openid, $msg);
                                    }
                                } else {
                                    if ($message_type == TM_COMMISSION_UPGRADE && !empty( $tm ['commission_upgrade'] ) && empty( $usernotice ['commission_upgrade'] )) {
                                        $message = $tm ['commission_upgrade'];
                                        $message = str_replace('[昵称]', $member ['nickname'], $message);
                                        $message = str_replace('[时间]', date('Y-m-d H:i:s', time()), $message);
                                        $message = str_replace('[旧等级]', $data ['oldlevel'] ['levelname'], $message);
                                        $message = str_replace('[旧一级分销比例]', $data ['oldlevel'] ['commission1'] . '%', $message);
                                        $message = str_replace('[旧二级分销比例]', $data ['oldlevel'] ['commission2'] . '%', $message);
                                        $message = str_replace('[旧三级分销比例]', $data ['oldlevel'] ['commission3'] . '%', $message);
                                        $message = str_replace('[新等级]', $data ['newlevel'] ['levelname'], $message);
                                        $message = str_replace('[新一级分销比例]', $data ['newlevel'] ['commission1'] . '%', $message);
                                        $message = str_replace('[新二级分销比例]', $data ['newlevel'] ['commission2'] . '%', $message);
                                        $message = str_replace('[新三级分销比例]', $data ['newlevel'] ['commission3'] . '%', $message);
                                        $msg = array( 'keyword1' => array( 'value' => !empty( $tm ['commission_upgradetitle'] ) ? $tm ['commission_upgradetitle'] : '分销等级升级通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                                        if (!empty( $templateid )) {
                                            m('message')->sendTplNotice($openid, $templateid, $msg);
                                        } else {
                                            m('message')->sendCustomNotice($openid, $msg);
                                        }
                                    } else {
                                        if ($message_type == TM_COMMISSION_BECOME && !empty( $tm ['commission_become'] ) && empty( $usernotice ['commission_become'] )) {
                                            $message = $tm ['commission_become'];
                                            $message = str_replace('[昵称]', $data ['nickname'], $message);
                                            $message = str_replace('[时间]', date('Y-m-d H:i:s', $data ['agenttime']), $message);
                                            $msg = array( 'keyword1' => array( 'value' => !empty( $tm ['commission_becometitle'] ) ? $tm ['commission_becometitle'] : '成为分销商通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                                            if (!empty( $templateid )) {
                                                m('message')->sendTplNotice($openid, $templateid, $msg);
                                            } else {
                                                m('message')->sendCustomNotice($openid, $msg);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }

        function perms(){
            return array( 'commission' => array( 'text' => $this->getName(), 'isplugin' => true, 'child' => array( 'cover' => array( 'text' => '入口设置' ), 'agent' => array( 'text' => '分销商', 'view' => '浏览', 'check' => '审核-log', 'edit' => '修改-log', 'delete' => '删除-log', 'user' => '查看下线', 'order' => '查看推广订单(还需有订单权限)', 'change' => '上级变更' ), 'level' => array( 'text' => '分销商等级', 'view' => '浏览', 'add' => '添加-log', 'edit' => '修改-log', 'delete' => '删除-log' ), 'apply' => array( 'text' => '佣金审核', 'view1' => '浏览待审核', 'view2' => '浏览已审核', 'view3' => '浏览已打款', 'view_1' => '浏览无效', 'check' => '审核-log', 'pay' => '打款-log', 'cancel' => '重新审核-log' ), 'notice' => array( 'text' => '通知设置-log' ), 'set' => array( 'text' => '基础设置-log' ) ) ) );
        }

        private function _getCountPriceByOrderId($orderid, $level){
            $goods = m('order')->getOrderGoods($orderid);

            $countPrice = array();

            if (!empty( $goods )) {
                foreach ($goods as $val) {
                    $countPrice[] = $val;
                }
            }

            return $countPrice;
        }

        private function _getRecord($order, $wealth, $level, $commPrice){
            global $_W;

            return array(
                'uniacid' => $_W['uniacid'],
                'mid' => $this->member['id'],
                'orderid' => $order['id'],
                'goods_id' => $wealth['goodsid'],
                'cg_money' => $wealth['price'],
                'o_create_time' => $order['createtime'],
                'o_send_time' => $order['sendtime'],
                'o_pay_time' => $order['paytime'],
                'o_finish_time' => $order['finishtime'],
                'o_invalid_time' => $wealth['invalidtime'.$level],
                'o_status' => $order['status'],
                'c_type' => '1',
                'c_rank' => $level,
                'c_rate' => 0,
                'c_money' => $commPrice,
                'c_apply_time' => $wealth['applytime'.$level],
                'c_check_time' => $wealth['checktime'.$level],
                'c_pay_time' => $wealth['paytime'.$level],
                'c_invalid_time' => $wealth['invalidtime'.$level],
                'c_content' => $wealth['content'.$level],
                'c_status' => $wealth['status'.$level],
            );
        }

    }
}